Data sheet used:
1. Group by date
- Use
convert()
function method
--根据年月
select convert(varchar(7),CreatTime,120)日期,COUNT(*) 次数,sum(Money)总数 from Orders
group by convert(varchar(7),CreatTime,120)
According to convert
the 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)
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
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