简体   繁体   中英

How to get the count of 2 values in the same column, in the same table?

I have a dataset about chess games, and in the winner column there are only 2 values: 'white' and 'black'. I want to show COUNT(winner) as WHITE_WINS and COUNT(winner) as BLACK_WINS. I tried inner joining the table by itself, however couldn't get the correct SQL query to do the job. How can I get a table like:

WHITE_WINS : 5986
BLACK_WINS : 5893

Use conditional aggregation:

SELECT
    COUNT(CASE WHEN winner = 'white' THEN 1 END) AS WHITE_WINS,
    COUNT(CASE WHEN winner = 'black' THEN 1 END) AS BLACK_WINS
FROM yourTable;

use sum()

select 
    sum(case when winner='white' then 1 else 0 end) as white,
    sum(case when winner='black' then 1 else 0 end) as black
from tableA

Use below one.

SELECT COUNT(CASE 
            WHEN winner = 'white'
                THEN 1
            ELSE 0
            END) AS WHITE_WINS
    ,COUNT(CASE 
            WHEN winner = 'black'
                THEN 1
            ELSE 0
            END) AS BLACK_WINS
FROM ChessTable;

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