sql—对列执行减法和求和操作

dldeef67  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(468)

我有这样一个输出:

Volume               c1                     c2
--------------------------------------------------
0                   1000                     0
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+'

但是,我需要得到如下输出。我试图从c2列的和中减去c1列的和,结果必须放在c2列下的第一行,如下所示:

Volume                c1                  c2
--------------------------------------------------
0                   1000              **1100**
1-20                 100                  10
20+                   50                  40

我该怎么做?
提前谢谢。

mcvgt66p

mcvgt66p1#

我只想做:

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是不必要的。

11dmarpk

11dmarpk2#

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
bnl4lu3b

bnl4lu3b3#

您可以使用下面的查询来获得所需的输出,并使用可以实现的cte表表达式。
cte为(从表t中依次选择大小写,当体积=0时,选择“0”,当体积<21时,选择“1-20”,当体积>=21时,选择“21+”,求和(ab)为c1,求和(xy)为c2,求和(ab)-求和(xy)为c,当体积=0时,选择“0”,当体积<21时,选择“1-20”,当体积>=21时,选择“1-20”,然后选择“21+”结束)
选择volume,c1,case when volume='0',然后(从cte中选择sum(c3)),否则从cte中选择c2 end c2

相关问题