具有各种列的各种范围的计数和总和

时间:2012-12-26 13:43:42

标签: sql oracle

经过一些帮助后,我在pl sql developer中获得了这些命令:

 SELECT  CASE
    WHEN t.aaa BETWEEN 1 AND 5000000 THEN '01'
    WHEN t.aaa BETWEEN 5000001 AND 7000000 THEN '02'
    WHEN t.aaa BETWEEN 7000001 AND 10000000 THEN '03'
    WHEN t.aaa BETWEEN 10000001 AND 30000000 THEN '04'
    WHEN t.aaa BETWEEN 30000001 AND 50000000 THEN '05'
    ELSE '06' END T
,count(t.bbb), sum(t.aaa)
FROM t.ccc
WHERE t.ddd IN  ('3','4','5','6','D','E','F')
AND t.zzz like '60%'
GROUP BY CASE 
   WHEN t.aaa BETWEEN 1 AND 5000000 THEN '01' 
   WHEN t.aaa BETWEEN 5000001 AND 7000000 THEN '02' 
   WHEN t.aaa BETWEEN 7000001 AND 10000000 THEN '03'
   WHEN t.aaa BETWEEN 10000001 AND 30000000 THEN '04'
   WHEN t.aaa BETWEEN 30000001 AND 50000000 THEN '05'
   ELSE '06' END order by 1;

结果是:

   T    COUNT(T.bbb)    SUM(T.aaa)
   1       1019           5519981
   2       878            8620000
   3       2250           16499000
   4       6844           4638E+11
   5       6061           691E+11
   6       915            8452192

所以我有各种行的计数和总和。现在我想知道如何为各列提供相同的行。我的意思是每COUNT(T.bbb)SUM(T.aaa)t.zzz(各种t.zzz)。

这些结果示例适用于行和2 t.zzz中的相同范围:

   T    COUNT(T.bbb)    SUM(T.aaa)   COUNT(T.bbb)     SUM(T.aaa)  
   1       1019          5519981       19             654321
   2       878           8620000       654            98765432
   3       2250          16499000      321            3454643
   4       6844          4638E+11      154            3213454
   5       6061          691E+11       2158           23132464
   6       915           8452192       145            341321321

而且我想要所有行甚至t.bbb的数量都是“0”。

1 个答案:

答案 0 :(得分:1)

目前还不完全清楚你要做什么,但似乎你想count()然后sum()使用一些额外的过滤。如果是这种情况,您可以使用与此类似的case语句:

SELECT  CASE
    WHEN t.aaa BETWEEN 1 AND 5000000 THEN '01'
    WHEN t.aaa BETWEEN 5000001 AND 7000000 THEN '02'
    WHEN t.aaa BETWEEN 7000001 AND 10000000 THEN '03'
    WHEN t.aaa BETWEEN 10000001 AND 30000000 THEN '04'
    WHEN t.aaa BETWEEN 30000001 AND 50000000 THEN '05'
    ELSE '06' END T,
  count(case when t.zzz like '60%' then t.bbb end) Count_BBB_60, 
  sum(case when t.zzz like '60%' then t.aaa end) Sum_AAA_60,
  count(case when t.zzz like '61%' then t.bbb end) Count_BBB_61,
  sum(case when t.zzz like '61%' then t.aaa end) Sum_AAA_61
FROM t.ccc
WHERE t.ddd IN  ('3','4','5','6','D','E','F')
GROUP BY CASE 
   WHEN t.aaa BETWEEN 1 AND 5000000 THEN '01' 
   WHEN t.aaa BETWEEN 5000001 AND 7000000 THEN '02' 
   WHEN t.aaa BETWEEN 7000001 AND 10000000 THEN '03'
   WHEN t.aaa BETWEEN 10000001 AND 30000000 THEN '04'
   WHEN t.aaa BETWEEN 30000001 AND 50000000 THEN '05'
   ELSE '06' END order by 1;