2014-12-04 86 views
0

下面提到的是我的兩個查詢:SQL查詢到在PIVOT結果顯示結合

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

我傾向於使用條件爲聚合支點。在這種情況下:

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格式。舉個例子,我不知道你的日期是在十二月還是四月和五月。

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; 

注:我將日期更改爲文化不變格式yyyyMMdd hh:mm:ss,但是,我不確定12/04/2014應該是4月12日還是12月4日(與該格式完全相同的問題),因此我可能會輸入錯誤的日期。我認爲你的意思是12月4日,就像今天一樣。

進一步的閱讀讀Bad habits to kick : mis-handling date/range queries