我正在进行查询,我需要在各种条件下找到总和。现在我的查询是:
sum(case when sum(C_amount)>3 then 6 else sum(C_amount) end) as S_C_amount
from table A group by item
但在第三种情况下我需要在When条件中使用sum函数
not a single group-by
。
我无法实现第三个条件。我收到klci = ['1015', '6399', '6888', '4162', '1023', '6947', '3034']
klse = '.KL'
tickers = klci + klse
print(tickers)
错误。
答案 0 :(得分:3)
如果没有一些示例数据,很难确定您要实现的目标,但在相同的组中使用SUM(SUM(value))
不会仅仅使用{{1所以看起来你可以使用:
Oracle 11g R2架构设置:
SUM(value)
查询1 :
CREATE TABLE A ( item, A_Amount, B_Amount, C_Amount, cond ) AS
SELECT 1, 1, 1, 1, 1 FROM DUAL UNION ALL
SELECT 1, 1, 1, 1, 2 FROM DUAL UNION ALL
SELECT 1, 1, 1, 1, 3 FROM DUAL UNION ALL
SELECT 1, 1, 1, 0, 4 FROM DUAL UNION ALL
SELECT 2, 2, 2, 2, 1 FROM DUAL UNION ALL
SELECT 2, 2, 2, 2, 2 FROM DUAL UNION ALL
SELECT 2, 2, 2, 2, 3 FROM DUAL UNION ALL
SELECT 2, 2, 2, 2, 4 FROM DUAL;
<强> Results 强>:
SELECT item,
SUM( CASE WHEN cond > 0 THEN A_amount END ) AS S_A_amount,
SUM( CASE WHEN cond > 0 THEN B_amount END ) AS S_B_amount,
CASE WHEN SUM(C_amount)>3 THEN 6 ELSE SUM(C_amount) END AS S_C_amount
FROM A
GROUP BY item
答案 1 :(得分:0)
这是你需要的吗?
select case
when sum_c_amount > 3 then
6
else
sum_c_amount
end as s_c_amount
from (select sum(c_amount) as sum_c_amount
from table a
group by item)
答案 2 :(得分:0)
将现有查询移动到子查询中,并将案例表达式逻辑放在外部查询图层中,例如
select
d.*
, case when S_C_amount > 3 then 6 else S_C_amount end
from (
select
item
, sum(case when condition then A_amount end) as S_A_amount
, sum(case when condition then B_amount end) as S_B_amount
, sum(case when condition then C_amount end) as S_C_amount
from t
group by item
) d
答案 3 :(得分:-1)
我会做这样的事情:
SELECT item,
sum(case when condition then A_amount end) as S_A_amount,
sum(case when condition then B_amount end) as S_B_amount,
sum(case when s_c_amount>3 then 6 else s_c_amount end) as S_C_amount
FROM (select item,
A_amount,
B_amount,
sum(C_amount) over (partition by item) as s_c_amount
from table A)
GROUP BY item