我想获得以下范围的计数和总和(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 ║
╚════════╩══════════════╩════════════╝
答案 0 :(得分: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;