如何在同一列的同一表中获得2个值的计数?

时间:2019-11-29 01:18:50

标签: sql

我有一个关于国际象棋游戏的数据集,在获胜者栏中只有2个值:“ white”和“ black”。我想将COUNT(获胜者)显示为WHITE_WINS,将COUNT(获胜者)显示为BLACK_WINS。我尝试单独内部连接表,但是无法获得正确的SQL查询来完成工作。我如何获得像这样的表:

WHITE_WINS | BLACK_WINS
5986 ......................... 5893

3 个答案:

答案 0 :(得分:3)

使用条件聚合:

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;

答案 1 :(得分:1)

使用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

答案 2 :(得分:1)

在1以下使用。

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;