2011-01-21 61 views
1

我有一個產品表中包含所有銷售爲一體的同時取得量..所以該表是:有關款項後訂購SQL問題

ID | product_department_id | product_id | quantity_sold

我需要列出所有的product_department_ids最好的2個銷售產品。任何想法如何我可以這樣做?

如果你可以在pl/sql中做到這將是偉大的,但SQL也可以!

謝謝!

回答

2
drop table quantity; 

create table quantity (
    id number primary key, 
    product_department_id number, 
    product_id number, 
    quantity_sold number, 
    unique (product_department_id, product_id) 
); 

insert into quantity values (1, 1, 1, 10); 
insert into quantity values (2, 1, 2, 20); 
insert into quantity values (3, 1, 3, 30); 

insert into quantity values (4, 2, 1, 60); 
insert into quantity values (5, 2, 2, 50); 
insert into quantity values (6, 2, 3, 40); 


select * from (
select quantity_sold, product_id, product_department_id, 
     row_number() over (partition by product_department_id order by quantity_sold desc) r 
    from quantity 
) where r < 3; 

編輯仍不能確定究竟是問,但如果組合prodcut /部門可以有multple條目那麼這將是:

drop table quantity; 

create table quantity (
    id number primary key, 
    product_department_id number, 
    product_id number, 
    quantity_sold number 
); 

insert into quantity values (1, 1, 1, 15); 
insert into quantity values (2, 1, 1, 15); 
insert into quantity values (3, 1, 1, 15); 
insert into quantity values (4, 1, 2, 20); 
insert into quantity values (5, 1, 3, 30); 

insert into quantity values (10, 2, 1, 60); 
insert into quantity values (11, 2, 2, 50); 
insert into quantity values (12, 2, 3, 40); 
insert into quantity values (13, 2, 3, 30); 


select * from (
select sum(quantity_sold), 
     product_id, product_department_id, 
     row_number() over (partition by product_department_id 
          order by sum(quantity_sold) desc 
     ) r 
    from quantity 
    group by product_department_id, product_id 
) where r < 3 
order by product_department_id, product_id; 
+0

你確定你可以和做的``命令解析函數內(quantity_sold)? – 2011-01-21 12:37:41

1

如果一個產品只能有一個部門,你可以簡單地order by

select product_department_id 
from YourTable 
where rownum < 3 
order by 
     quantity_sold desc