0

我想获得以下范围(10-20、21-30、31-40)的计数和总和。我怎样才能修改这个查询来得到它?

select count (t.aaa), sum (t.bbb)
from xxx t
where t.qqq IN  ('3')
and t.www like 'A'
and t.eee >= TO_DATE('2008/03/20','YYYY/MM/DD')
and t.eee <= TO_DATE('2009/03/21','YYYY/MM/DD')
and t.ttt >= 10 and t.ttt <= 20

输出应如下所示:

╔════════╦══════════════╦════════════╗
║ TRANGE ║ COUNT(t.aaa) ║ SUM(t.bbb) ║
╠════════╬══════════════╬════════════╣
║ 10-20  ║          340 ║ 4981620000 ║
║ 21-30  ║          239 ║ 3999425000 ║
║ 31-40  ║          199 ║ 4076525000 ║
╚════════╩══════════════╩════════════╝
4

1 回答 1

2

听起来您可能想按 t.www 和每个范围进行分组。案例可以将每个数字转换为范围值,然后可以在分组依据中使用。

SELECT CASE 
   WHEN t.ttt BETWEEN 10 AND 20 THEN '10-20'
   WHEN t.ttt BETWEEN 21 AND 30 THEN '21-30'
   ELSE '31-40' END TRange
   , count(t.aaa), sum(t.bbb)
FROM xxx t
WHERE t.qqq IN  ('3')
AND t.www IN ('A','B','C','D')
AND t.eee >= TO_DATE('2008/03/20','YYYY/MM/DD')
AND t.eee <= TO_DATE('2009/03/21','YYYY/MM/DD')
AND t.ttt BETWEEN 10 AND 40
GROUP BY CASE 
   WHEN t.ttt BETWEEN 10 AND 20 THEN '10-20'
   WHEN t.ttt BETWEEN 21 AND 30 THEN '21-30'
   ELSE '31-40' END;

SQLFiddle。

于 2012-12-11T15:42:19.073 回答