Oracle實現統計

風靈使發表於2018-06-29

ORACLEGROUP BY 來分組日期欄位 按月分組

SELECT to_char(日期欄位,'yyyymm'),sum(*) 
FROM [TableName] 
group by to_char(日期欄位,'yyyymm');

oracle按每天,每週,每月,每季度,每年查詢統計資料

//按天統計
select count(dataid) as 每天運算元量, sum()
from tablename
group by trunc(createtime, 'DD'))
//按自然周統計 
select to_char(date,'iw'),sum() 
 from  tablename
 group by to_char(date,'iw') 
//按自然月統計 
select to_char(date,'mm'),sum() 
 from   tablename
 group by to_char(date,'mm') 
 //按季統計 
select to_char(date,'q'),sum() 
 from  tablename
 group by to_char(date,'q')
 //按年統計 
select to_char(date,'yyyy'),sum() 
 from  tablename
 group by to_char(date,'yyyy')

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 年度;  

這裡寫圖片描述

相關文章