我是Oracle SQL的新手(但有一些基本的SQL知识)。请考虑以下数据结构:
Region Plan Code SM_Name Charge Commission
EMEA SM abc john smith DARK 10
Asia SM def bob jones MAKER 40
AmericasSM ghi chris eng TAKER 30
AmericasSM xyz bob marks FUND 40
Asia SM def brian bee DARK 10
我想创建一个SELECT语句,它将按佣金汇总佣金并将其放在两个单独的列中。
所以喜欢这个
Region Plan Code SM_Name DIRECT TRX
EMEA SM abc john smith 10
Asia SM def bob jones 40
AmericasSM ghi chris eng 30
AmericasSM xyz bob marks 40
Asia SM def brian bee 10
我试图使用CASE语句从我所做的研究中创建这个,但它并不是很有效。我的SQL如下:
SELECT a.REGION, 'SM', a.TRADING_CODE, a.SM,
CASE
WHEN a.CHARGE = 'FUND' THEN SUM(a.COMMISSION)
END AS DIRECT,
CASE
WHEN a.CHARGE IN ('DARK', 'MAKER', 'TAKER') THEN SUM(a.COMMISSION)
END AS TRX
FROM WORK_COMMISSION_RESULTS a
GROUP BY a.REGION, 'SM', a.TRADING_CODE, a.SM;
运行代码时出现错误“不是GROUP BY表达式”。我知道也许IF语句也可以运行,但我有点迷失。
任何人都可以协助让我朝着正确的方向前进吗?
答案 0 :(得分:1)
将SUM
移到之外 CASE
声明:
SELECT a.REGION, 'SM', a.TRADING_CODE, a.SM,
SUM(CASE
WHEN a.CHARGE = 'FUND' THEN a.COMMISSION
END) AS DIRECT,
SUM(CASE
WHEN a.CHARGE IN ('DARK', 'MAKER', 'TAKER') THEN a.COMMISSION
END) AS TRX
FROM WORK_COMMISSION_RESULTS a
GROUP BY a.REGION, 'SM', a.TRADING_CODE, a.SM;
答案 1 :(得分:1)
使用条件聚合:
select Region, Plan, Code, SM_Name,
sum(case when charge = 'FUND' then Commission end) as Direct,
sum(case when charge <> 'FUND' then Commission end) as TRX
from WORK_COMMISSION_RESULTS wcr
group by Region, Plan, Code, SM_Name ;