[英]Oracle How To Compare Rows?
我有桌子。
SALESMAN_REGION
(
SALESMAN_ID INTEGER,
REGION_ID INTEGER
);
SALESMAN
(
SALESMAN_ID INTEGER,
SALESMAN_NAME VARCHAR2(50)
);
TABLE SALES
(
SALE_ID INTEGER,
PRODUCT_ID INTEGER,
SALESMAN_ID INTEGER,
YEAR INTEGER,
Quantity INTEGER,
PRICE INTEGER
);
而且我需要此信息,其中托尼的銷售額比凱文高。 我寫了這個查詢
select s.region_id,sum(s.quantity),s.salesman_id from sales s where s.salesman_id in (
select sr.salesman_id from salesman_region sr
inner join
salesman sm on sm.salesman_id = sr.salesman_id
where
sm.salesman_name = 'Tony' or sm.salesman_name = 'Kevin') group by s.region_id ,s.salesman_id order by s.region_id;
輸出為:
REGION_ID SUM(S.QUANTITY) SALESMAN_ID
1 10 1776 10
2 10 1603 30
3 20 1813 10
4 20 1479 30
5 30 1218 10
6 30 1516 30
但是我不知道如何比較這個或其他方式。 誰能幫我?
我將使用條件聚合來解決這個問題:
select s.region_id,
sum(case when sm.salesman_name = 'Tony' then s.quantity else 0 end) as QTony,
sum(case when sm.salesman_name = 'Kevin' then s.quantity else 0 end) as QKevin
from salesman_region sr inner join
salesman sm
on sm.salesman_id = sr.salesman_id inner join
sales s
on s.sales_man_id = sm.salesman_id
group by s.region_id
having (sum(case when sm.salesman_name = 'Tony' then s.quantity else 0 end) >
sum(case when sm.salesman_name = 'Kevin' then s.quantity else 0 end)
)
注意:為使此方法有效,它假定推銷員僅在一個地區。 如果不是這樣,則您的數據結構無法回答您的問題,因為您不知道哪個銷售在哪個地區。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.