Sql 列上的减法和求和操作
我有这样一个输出:Sql 列上的减法和求和操作,sql,oracle,group-by,Sql,Oracle,Group By,我有这样一个输出: Volume c1 c2 -------------------------------------------------- 0 1000 0 1-20 100 10 20+ 50 40
Volume c1 c2
--------------------------------------------------
0 1000 0
1-20 100 10
20+ 50 40
Volume c1 c2
--------------------------------------------------
0 1000 **1100**
1-20 100 10
20+ 50 40
我通过以下方式获得此输出:
SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'
我该怎么做
提前感谢。您可以使用下面的查询获得所需的输出
WITH x
AS
(
SELECT
case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' as Volume,
sum(ab) as c1,
sum(xy) as c2
FROM
table t
GROUP BY
CASE when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+'
)
SELECT x.Volume, x.c1, (CASE WHEN x.Volume = 0
THEN (SELECT SUM(x2.c1 - x2.c2)
FROM x AS x2)
ELSE x.c2 END)
FROM x
使用CTE表表达式可以实现
以Cte为例
选择
当卷=0时为“0”,当卷=21时为“0”,然后将“21+”作为卷,
sumab作为c1,
sumxy作为c2,
sumab sumxy as c
从…起
表t
分组
当卷=0时为“0”,当卷=21时为“0”,则“21+”结束
选择volume,c1,case when volume='0',然后从cte中选择sumc3 else c2 end c2 from cte您可以使用下面的查询来获得所需的输出 使用CTE表表达式可以实现 以Cte为例 选择 当卷=0时为“0”,当卷=21时为“0”,然后将“21+”作为卷, sumab作为c1, sumxy作为c2, sumab sumxy as c 从…起 表t 分组 当卷=0时为“0”,当卷=21时为“0”,则“21+”结束 选择volume,c1,当volume='0'时选择case,然后从cte中选择sumc3,否则从cte中选择c2结束c2
SELECT (case when volume = 0 then '0' when volume < 21 then '1-20' when volume>=21 then '21+' end) as Volume,
sum(ab) as c1,
(case when volume = 0
then sum(sum(ab)) over () - sum(sum(xy))
else sum(xy)
end) as c2
FROM table t
GROUP BY (case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' end);
当您可以简单地使用窗口函数时,子查询和CTE是不必要的。我只需要:
SELECT (case when volume = 0 then '0' when volume < 21 then '1-20' when volume>=21 then '21+' end) as Volume,
sum(ab) as c1,
(case when volume = 0
then sum(sum(ab)) over () - sum(sum(xy))
else sum(xy)
end) as c2
FROM table t
GROUP BY (case when volume=0 then '0' when volume <21 then '1-20' when volume>=21 then '21+' end);
当您可以简单地使用窗口函数时,子查询和CTE是不必要的。您的问题不清楚。你们能详细说明一下吗?请展示一下样本数据-不清楚我想减去C1的和。。。意思是,你的问题不清楚。你们能详细说明一下吗?请展示一下样本数据-不清楚我想减去C1的和。。。方法