使用 MySQL 查询选择多个总和并将它们显示在单独的列中

2022-01-22 00:00:00 pivot sql mysql

假设我有一个假设的表格,用来记录某些游戏中的某个玩家何时得分:

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
mike    04
bob     06

如何获得每个玩家的总得分并在一个查询中并排显示?

How would I get the sum of each player's scores and display them side by side in one query?

总分表​​

bob   mike
16     07

我的(伪)查询是:

SELECT sum(points) as "Bob" WHERE name="bob",
       sum(points) as "Mike" WHERE name="mike"
  FROM score_table

推荐答案

您可以手动"旋转数据:

You can pivot your data 'manually':

SELECT SUM(CASE WHEN name='bob' THEN points END) as bob,
       SUM(CASE WHEN name='mike' THEN points END) as mike
  FROM score_table

但如果你的玩家列表是动态的,这将不起作用.

but this will not work if the list of your players is dynamic.

相关文章