2

我有一个如下的 T-SQL 查询,它查询一个包含搜索数据的表并获取搜索时间和该搜索时间的行数。

SELECT DATEPART(HOUR, aps.CreatedOn) AS SearchHour, COUNT(*) AS ItemCOUNT 
FROM ASearches aps
GROUP BY DATEPART(HOUR, aps.CreatedOn)
ORDER BY SearchHour;

如您所见,这不会产生很好的结果。但是,我知道如果为此使用数据透视表并将小时数作为列名,那会更好。我试过了,但到目前为止我一直失败。

知道怎么做吗?

4

1 回答 1

8

像这样的东西:

SELECT *
  FROM (SELECT DATEPART(HOUR, CreatedOn) AS SearchHour 
          FROM ASearches) aps
 PIVOT (COUNT([SearchHour]) FOR SearchHour IN 
         ( [0],  [1],  [2],  [3],  [4],  [5], 
           [6],  [7],  [8],  [9], [10], [11], 
          [12], [13], [14], [15], [16], [17], 
          [18], [19], [20], [21], [22], [23])) as pvt
于 2012-06-14T11:37:44.797 回答