Oracle 分組統計,按照天、月份周和自然周、月、季度和年

Oracle 分組統計,按照天、月份周和自然周、月、季度和年

做報表統計時會經常用到 周,月,季度,年進行分組統計,所以結合網路搜尋推薦的sql,總結如下:

-- 按天統計
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')
ORDER by 天 NULLS  LAST;

-- 按自然周的日期統計 
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 周;

-- 按自然周統計 
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 周;

-- 按自然月統計 
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 月份;

-- 按季統計 
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;

--按年統計 
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 年度;