2017-06-13 69 views
0

我正在使用數據透視表來生成一個交叉列表報表來彙總使用MSSQL Server的數據。但是,當我運行我的查詢時,它沒有產生我期望的結果。在MSSQL Server中使用PIVOT計數聚合不起作用?

這是SQL查詢樞軸:

select Station, 
     [1] as Good, 
     [3] as Bad, 
     [5] as Deactivated, 
     [6] as Deleted 
     --StateCount 
from 
(
select m.MetaData1 as Station, 
     t.ID, 
     --m.StateID, 
     count(t.[State]) as StateCount 
from MasterTags m inner join TagStates t on t.ID = m.StateID 
where (m.MetaData1 is not null and m.MetaData1 != '') and (m.PIServerID = 1) 
group by m.MetaData1, t.ID, m.StateID, t.[State] 
) as result 
PIVOT (count(result.StateCount) for ID in ([1], [3], [5], [6])) pvt 

結果:

Station | Good | Bad | Deactivated | Deleted | StateCount 
------- +-------+------+-------------+---------+----------- 
ABY  | 0 | 0 |  0  | 1  |  4 
ABY  | 0 | 1 |  0  | 0  | 18 
ABY  | 1 | 0 |  0  | 0  | 40 
FTB  | 0 | 1 |  0  | 0  | 10 
FTB  | 1 | 0 |  0  | 0  | 121 
KIK  | 0 | 1 |  0  | 0  |  1 
KIK  | 1 | 0 |  0  | 0  | 45 

我已經包含上述StateCount列顯示實際count(t.[State])值。但是,對於最終結果集中的每個列(Good,Bad,Deactivated,Deleted),我得到的值爲1。我期望StateCount值將是這些列的數據(如下所示)。

預期輸出:

Station | Good | Bad | Deactivated | Deleted 
------- +-------+------+-------------+-------- 
ABY  | 40 | 18 |  0  | 4 
FTB  | 121 | 10 |  0  | 0 
KIK  | 45 | 1 |  0  | 0 

這是我的第一次在一個表值表達式使用樞軸關係運算符。也許我不太瞭解如何正確使用它。我的透視查詢是否錯誤?

任何幫助,非常感謝。

+0

'group by m.MetaData1,t.ID,m.StateID,t。[State]' - 檢查分組並重試。也就是說,運行查詢*而不用* PIVOT。至少,t.ID可能是一次一行地「分組」。 – user2864740

+0

@ user2864740我已經在表值表達式中擁有該分組。爲了實現交叉製表數據,我可能在查詢中需要PIVOT。這是否可以在一個使用PIVOT的select語句中實現,還是應該創建一個存儲過程來處理數據? – Juniuz

+0

以及你已經計算select(count(t。[State])中的數字爲StateCount),當它涉及到樞紐時,你已經只有一行用於該特定ID,並且它計數一個。因此,在數據透視中不要使用計數。只需使用一個選擇即PIVOT(result.StateCount用於[[1],[3],[5],[6]))pvt – Sam

回答

0

我發現我的sql查詢的結構不正確,我想返回正確的結果。爲了達到我想要的輸出,這就是我用PIVOT關係運算符用表值表達式編寫sql語句的方法。

select Station, 
     [1] as Good, 
     [3] as Bad, 
     [5] as Deactivated, 
     [6] as Deleted 
from 
(
select m.MetaData1, 
     m.MetaData1 as Station, 
     t.ID, 
from MasterTags m inner join TagStates t on t.ID = m.StateID 
where (m.MetaData1 is not null and m.MetaData1 != '') and (m.PIServerID = 1) 
group by m.MetaData1, t.ID 
) as result 
PIVOT (count(result.MetaData1) for ID in ([1], [3], [5], [6])) pvt 

這給了我正確的結果。