SQL Server is grouped by date and time period (a group of every three hours)

Data sheet used:
Insert picture description here

1. Group by date

  1. Use convert()function method
--根据年月
select convert(varchar(7),CreatTime,120)日期,COUNT(*) 次数,sum(Money)总数 from Orders
group by convert(varchar(7),CreatTime,120)

According to convertthe first parameter of, the length of the result is set to be more grouped by year, month or day, etc.

2017-09 Length 7 varchar(7)

2017-09-01 Length 10 varchar(10)

--根据年月日
select convert(varchar(10),CreatTime,120)日期,COUNT(*) 次数,sum(Money)总数 from Orders
group by convert(varchar(10),CreatTime,120)

Insert picture description here
Insert picture description here
2. First find out the corresponding year, month, day, etc., and then group according to the query field

--或者
select YEAR(CreatTime),month(CreatTime),COUNT(*) 次数,sum(Money)总数 from Orders
group by month(CreatTime),YEAR(CreatTime)
order by,asc

Insert picture description here

2. Group according to time period (one group every three hours)

dataname: Returns the character string representing the specified date part of the specified date. One parameter represents the returned format, and the second parameter is the specific value

dw: Day of the week, qq, q: quarter, yy, yyyy: year, mm, m: month, dd, d: day, hh: hour, mi, n: minute ss, s: second, ms: millisecond

select CONVERT(varchar(11),convert(varchar(2),datename(hh,CreatTime) / 3 *3)+':00~'+convert(varchar(2),
row_number() over(order by datename(hh,CreatTime) / 3)*3-1)+':59') 时间段
,COUNT(*)次数,sum(Money)总数 from Orders
group by datename(hh,CreatTime) / 3

Insert picture description here

Guess you like

Origin blog.csdn.net/WuLex/article/details/114658720