我有桌子。
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
但我不知道如何比较这种或其他方式。谁能帮我?
答案 0 :(得分:1)
我会使用条件聚合来解决这个问题:
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)
)
注意:为此,它假定销售人员只在一个地区。如果不是这样,那么您的数据结构无法回答您的问题,因为您不知道哪些销售位于哪些区域。