我有一个包含以下列的表:
date | station
Date
是datetime
列。
Station
只是1到110之间的数字。
我需要返回上个月的1到26之间的最频繁站点值。 我今天已经做到了,并且可以正常工作(下面的代码)。但是我不知道整个月该怎么做。
SELECT count(1)
FROM table
WHERE YEAR(Time_Stamp) = YEAR(GETDATE()) AND
MONT(Time_Stamp) = MONTH(GETDATE()) AND
DAY(Time_Stamp) = DAY(GETDATE()) AND
station BETWEEN 1 AND 26
GROUP BY station
ORDER BY count(1) desc
答案 0 :(得分:0)
只需使用WHERE子句中的数据列:
SELECT COUNT(*), station
FROM t
WHERE station BETWEEN 1 AND 26
AND date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
AND date < DATEADD(DAY, 1, EOMONTH(GETDATE(), 0))
GROUP BY station
ORDER BY COUNT(*) DESC
EOMONTH
需要SQL Server 2012或更高版本。