我的代码是:
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 request_created_date
ORDER BY request_week
在我得到的输出中,我有两行,其中request_week是36行,7行是37行。我想要的是将这样的列组合成一行。
答案 0 :(得分:1)
如果要使用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