2014-11-22 141 views
0

我的下一個SQL Server表:的SQL Server交叉聯接查詢

Machine | Result 
----------------- 
M2  | 0 
M1  | 1 
M3  | 0 
M1  | 1 
M2  | 1 
M1  | 0 
M2  | 0 
M1  | 1 
M3  | 0 
M1  | 1 
M3  | 0 

我需要得到像這樣的報告:

Machine | Count 0's | Count 1's 
-------------------------------- 
M1  | 1  | 4 
M2  | 2  | 1 
M3  | 3  | 0 

我都試過,沒有sucess下一個查詢:

SELECT A, B 
FROM 
(SELECT COUNT(*) as A 
FROM MY_TABLE 
WHERE Result = 0) 
GROUP BY Machine) a 
CROSS JOIN 
(SELECT COUNT(*) as B 
FROM MY_TABLE 
WHERE Result = 1) 
GROUP BY Machine) b 

你能幫助我嗎?提前致謝!

回答

2

您可以有條件聚集做到這一點:

select machine, 
     sum(case when result = 0 then 1 else 0 end) as num_0, 
     sum(case when result = 1 then 1 else 0 end) as num_1 
from my_table 
group by machine; 
+0

謝謝,完美的作品! – user3658439 2014-11-22 23:16:36