下面提到的是我的两个问题:
SELECT WINDOWS_NT_LOGIN, COUNT(DPS_NUMBER) as TotalDPS
FROM DispatcherProductivity
WHERE DPS_Processed_Time_Stamp>='12/04/2014 10:30 AM'
AND DPS_Processed_Time_Stamp<='12/05/2014 10:30 AM'
GROUP BY WINDOWS_NT_LOGIN
ORDER BY TotalDPS
SELECT STATUS, COUNT(DPS_NUMBER) AS TotalDPS
FROM DispatcherProductivity
WHERE DPS_Processed_Time_Stamp>='12/04/2014 10:30 AM'
AND DPS_Processed_Time_Stamp<='12/05/2014 10:30 AM'
GROUP BY STATUS
ORDER BY TotalDPS
他们各自的结果是:
WINDOWS_NT_LOGIN TotalDPS
A_S 72
T_I_S 133
STATUS TotalDPS
ID 1
Can 2
NHD 3
SED 14
Ord 185
我想以这种格式得到结果:
WINDOWS_NT_LOGIN ID Can NHD SED Ord
A_S 2 70
T_I_S 1 2 3 12 115
由于
答案 0 :(得分:1)
您可以使用PIVOT
功能:
SELECT pvt.WINDOWS_NT_LOGIN,
pvt.[ID],
pvt.[Can],
pvt.[NHD],
pvt.[SED],
pvt.[Ord]
FROM ( SELECT WINDOWS_NT_LOGIN, STATUS, DPS_NUMBER
FROM DispatcherProductivity
WHERE DPS_Processed_Time_Stamp>='20141204 10:30:00'
AND DPS_Processed_Time_Stamp<='20141205 10:30:00'
) AS t
PIVOT
( COUNT(DPS_NUMBER)
FOR STATUS IN ([ID], [Can], [NHD], [SED], [Ord])
) AS pvt;
N.B。我将您的日期更改为文化不变格式yyyyMMdd hh:mm:ss
,但是,我不确定12/04/2014
是否应该是4月12日或12月4日(这种格式的确切问题),所以有可能我把错误的日期写进了。我认为你的意思是12月4日,就像今天一样。
如需进一步阅读,请阅读Bad habits to kick : mis-handling date / range queries
答案 1 :(得分:0)
我倾向于使用条件聚合来实现支点。在这种情况下:
SELECT WINDOWS_NT_LOGIN, COUNT(DPS_NUMBER) as TotalDPS,
SUM(CASE WHEN status = 'ID' THEN DPS_Number END) as ID,
SUM(CASE WHEN status = 'Can' THEN DPS_Number END) as Can,
SUM(CASE WHEN status = 'NHD' THEN DPS_Number END) as NHD,
SUM(CASE WHEN status = 'SED' THEN DPS_Number END) as SED,
SUM(CASE WHEN status = 'Ord' THEN DPS_Number END) as Ord
FROM DispatcherProductivity
WHERE DPS_Processed_Time_Stamp >= '12/04/2014 10:30 AM' AND
DPS_Processed_Time_Stamp <= '12/05/2014 10:30 AM'
GROUP BY WINDOWS_NT_LOGIN;
我还建议您在您的日期使用YYYY-MM-DD格式。我不知道你的日期是12月,4月和5月。