如何组合具有相同数据的同一列中的多个行?

时间:2013-10-11 14:31:12

标签: sql sql-server sql-server-2008 subquery

我的代码是:

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

1 个答案:

答案 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