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

后端 未结 6 1151
无人及你
无人及你 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:28

    Are the player names all known up front? If so, you can do:

    SELECT SUM(CASE WHEN name = 'bob'  THEN points ELSE 0 END) AS bob,
           SUM(CASE WHEN name = 'mike' THEN points ELSE 0 END) AS mike,
           ... so on for each player ...
      FROM score_table
    

    If you don't, you still might be able to use the same method, but you'd probably have to build the query dynamically. Basically, you'd SELECT DISTINCT name ..., then use that result set to build each of the CASE statements, then execute the result SQL.

提交回复
热议问题