user3658439
user3658439

Reputation: 163

SQL Server Cross Join Query

I have the next SQL Server table:

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

I need to get a report like this:

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

I have tried the next query with no 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

Can you help me?. Thanks in advance!

Upvotes: 0

Views: 40

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271051

You can do this with conditional aggregation:

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;

Upvotes: 2

Related Questions