我想将SQL Server数据库中的数据分组为每小时报告

时间:2014-12-03 16:37:00

标签: sql-server

我想问社群如下:

我有一个表Productivity,其中包含以下列:

SerialNumber (Primary Key) - Identity Column
Processed_Time_Stamp - DateTime
Login_ID - nvarchar(255)
Order_Number - Float
Order_Location - Float
Status - nvarchar(255)

我正在使用此查询:

SELECT 
    Login_ID, COUNT(Login_ID) as [Total Number]
FROM 
    Productivity
WHERE 
    Processed_Time_Stamp >= '2014-12-03 10:30:00.000' 
    AND Processed_Time_Stamp <= '2014-12-04 10:30:00.000'
GROUP BY 
    Login_ID

这给了我这些结果:

Login_ID    Total Number
------------------------
Zohaib          10
XYX             20

但是,我想以下列格式解决这个问题:

Login_ID   10 AM   11 AM
-------------------------
zohaib       5       5
XYZ          7      13

提前致谢

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

WITH DATA
AS
(
SELECT Login_ID, 1 AS N, DATEPART(HOUR, Processed_Time_Stamp) H
FROM Productivity
WHERE Processed_Time_Stamp >='2014-12-03 10:30:00.000' and Processed_Time_Stamp <= '2014-12-04 10:30:00.000'
)
SELECT Login_ID, [10], [11]
FROM DATA
PIVOT (SUM(N) FOR H IN ([10], [11])) AS P

希望这有帮助。

干杯。