Select multiple sums with MySQL query and display them in separate columns

后端 未结 6 1146
无人及你
无人及你 2021-01-02 03:38

Let\'s say I have a hypothetical table like so that records when some player in some game scores a point:

name   points
------------
bob     10
mike    03
mi         


        
6条回答
  •  轮回少年
    2021-01-02 04:04

    In pure sql:

    SELECT
        sum( (name = 'bob') * points) as Bob,
        sum( (name = 'mike') * points) as Mike,
        -- etc
    FROM score_table;
    

    This neat solution works because of mysql's booleans evaluating as 1 for true and 0 for false, allowing you to multiply truth of a test with a numeric column. I've used it lots of times for "pivots" and I like the brevity.

提交回复
热议问题