有关订购后的订购的问题

时间:2011-01-21 12:31:25

标签: sql plsql

我有一个产品表,其中包含一次制作的所有销售数量。所以表格是:

id | product_department_id | product_id | quantity_sold

我需要列出所有product_department_ids最好的2个畅销产品。我有什么想法可以这样做吗?

如果你能在pl / sql中实现它会很棒但是sql也可以!

谢谢!

2 个答案:

答案 0 :(得分: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 / department可以有多个条目,那么它将是:

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;

答案 1 :(得分:1)

如果某个产品只能有一个部门,您只需order by

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