1. 程式人生 > >sqlserver中如何實現時間按月,日,小時等時間分組查詢

sqlserver中如何實現時間按月,日,小時等時間分組查詢

--按照月份統計
select count(id) cnt,datepart(mm,time) [Month]
from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(mm,time)
--按照日統計
select count(id) cnt,datepart(dd,time) [Day]
from [table]
where time between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'
group by datepart(dd,time)
--按照小時統計
select count(id) cnt,datepart(hh,time) [Hour]

from [table]
where [time] between '2007/09/08 09:10:43' and '2007/10/09 04:32:37'

group by datepart(hh,time)

--按年月分組

select datename(year,dt)+datename(month,dt)as 年月 ,sum(d) as 統計 from abc group by datename(year,dt)+datename(month,dt)

--按照旬統計

 select case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else
'下旬' end as 旬, sum(d) as 統計 from abc group by case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else '下旬' end

--按 年+旬 分組統計

select datename(year,dt)+datename(month,dt)+case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else '下旬' end as 日期, sum(d) as 統計
 from abc 
 group by
datename(year,dt)+datename(month,dt)+case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else '下旬' end