2011-01-21 4 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을)를'명령을 할 수있는 확실한가요? –

+0

'product_id, product_department'로 파티션하면, 모든 제품 - 부서 조합의 상위 3 행을 나열합니다. 아마 테이블 전체일까요? – Andomar

+0

예, 나는 지금 문제를 해결하고 수정했습니다. –

1

제품이 하나 개의 부서가 할 수있는 경우 , 당신은 할 수 단순히 order by :

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