如果要使用 GROUP BY 子句,则必须在 GROUP BY 中包含除计算字段之外的所有字段:
SELECT datepart(year, request_created_date) AS request_year,
datepart(month, request_created_date) AS request_month,
datepart(week, request_created_date) AS request_week,
count(request_id) AS request_count
FROM nyc311_requests
GROUP BY datepart(year, request_created_date),
datepart(month, request_created_date),
datepart(week, request_created_date)
ORDER BY request_week
或者,如果您想要一个更清晰的查询:
SELECT M.*, count(*) AS request_count FROM
(
SELECT datepart(year, request_created_date) AS request_year,
datepart(month, request_created_date) AS request_month,
datepart(week, request_created_date) AS request_week
FROM nyc311_requests
)AS M
GROUP BY M.request_year, M.request_month, M.request_week
ORDER BY M.request_week