Oracle 分组统计,按照天、月份周和自然周、月、季度和年

做报表统计时会经常用到 周,月,季度,年进行分组统计,所以结合网络搜索推荐的sql,总结如下

1
2
3
4
5
6
-- 按天统计
select to_char(t.CREATED+15/24, 'YYYY-MM-DD') as 天,sum(1) as 数量
from TB_EXT_TRADE t
WHERE
t.TID LIKE 'SC%' OR t.TID LIKE 'WSC%'
group by to_char(t.CREATED+15/24, 'YYYY-MM-DD') --trunc(t.CREATED, 'DD')

1
2
3
4
5
6
7
-- 按自然周的日期统计 
select to_char(next_day(t.CREATED+15/24 - 7,2),'YYYY-MM-DD') AS 周,sum(1) as 数量
from TB_EXT_TRADE t
WHERE
t.TID LIKE 'SC%' OR t.TID LIKE 'WSC%'
group by to_char(next_day(t.CREATED+15/24 - 7,2),'YYYY-MM-DD')
ORDER BY 周;

1
2
3
4
5
6
7
-- 按自然周统计 
select to_char(t.CREATED,'iw') AS 周,sum(1) as 数量
from TB_EXT_TRADE t
WHERE
t.TID LIKE 'SC%' OR t.TID LIKE 'WSC%'
group by to_char(t.CREATED,'iw')
ORDER BY 周;

1
2
3
4
5
6
7
8
-- 按自然月统计 
select to_char(t.CREATED,'YYYY-MM') as 月份,sum(1) as 数量
from TB_EXT_TRADE t
WHERE
t.TID LIKE 'SC%' OR t.TID LIKE 'WSC%'
GROUP BY
to_char(t.CREATED,'YYYY-MM') -- to_char(t.CREATED+15/24,'yyyy-mm') 不大准确
ORDER BY 月份;

1
2
3
4
5
6
7
-- 按季统计 
select to_char(t.CREATED,'q') 季度,sum(1) as 数量
from TB_EXT_TRADE t
WHERE
t.TID LIKE 'SC%' OR t.TID LIKE 'WSC%'
group by to_char(t.CREATED,'q')
ORDER BY 季度 NULLS LAST;

1
2
3
4
5
6
7
--按年统计 
select to_char(t.CREATED,'yyyy') AS 年度,sum(1) as 数量
from TB_EXT_TRADE t
WHERE
t.TID LIKE 'SC%' OR t.TID LIKE 'WSC%'
group by to_char(t.CREATED,'yyyy')
ORDER BY 年度;

如果你觉得这篇文章对你有用,欢迎赞赏哦~
本文结束啦 感谢您阅读
0%