sqlserver中如何实现时间按月,日,小时等时间分组查询

时间:2021-03-16 15:11:24
--按照月份统计
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