0

我的代码是:

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。我想要的是将这样的列组合成一行。

4

1 回答 1

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
于 2013-10-11T15:02:03.210 回答