1. 程式人生 > 資料庫 >SQL語句統計每天、每月、每年的資料

SQL語句統計每天、每月、每年的資料

統計每月

--這種形式只能查資料庫存在的日期  比如資料庫只有到六月分的 那六月以後的就沒有
select 需要的欄位,month (  日期欄位) as 月份,sum( 要統計的欄位) as 總數
from
  表
where
  year (  日期欄位) = DATEPART(year,GETDATE())    -- 要查某年  這裡獲取當年
group by
 需要的欄位,month (  日期欄位)

----這種形式自定義月份  可查全年沒有則為0
select  需要的欄位,sum(case when  datepart(month,日期欄位)=1 then 1 else 0 end) as '1月',日期欄位)=2 then 1 else 0 end) as '2月',日期欄位)=3 then 1 else 0 end) as '3月',日期欄位)=4 then 1 else 0 end) as '4月',日期欄位)=5 then 1 else 0 end) as '5月',日期欄位)=6 then 1 else 0 end) as '6月',日期欄位)=7 then 1 else 0 end) as '7月',日期欄位)=8 then 1 else 0 end) as '8月',日期欄位)=9 then 1 else 0 end) as '9月',日期欄位)=10 then 1 else 0 end) as '10月',日期欄位)=11 then 1 else 0 end) as '11月',日期欄位)=12 then 1 else 0 end) as '12月'
    from 表 
    where year (  日期欄位) = DATEPART(year,GETDATE())   group by 分組的欄位-- 要查某年  這裡獲取當年
1、每年
select year(ordertime) 年,
sum(Total) 銷售合計
from 訂單表
group by year(ordertime)

2、每月
select year(ordertime) 年,
month(ordertime) 月,sum(Total) 銷售合計
from 訂單表
group by year(ordertime),
month(ordertime

3、每日
select year(ordertime) 年,
month(ordertime) 月,day(ordertime) 日,
sum(Total) 銷售合計
from 訂單表
group by year(ordertime),
month(ordertime),day(ordertime)

另外每日也可以這樣:
select convert(char(8),ordertime,112) dt,
sum(Total) 銷售合計
from 訂單表
group by convert(char(8),112)