简体   繁体   中英

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM