使用一些行值作为列SQL

时间:2013-12-16 19:52:36

标签: mysql sql

我希望列的内容如下:

KILL, DEATH, WIN, playerName

这是应该应用的结果集 enter image description here

这是我用来获取结果集的查询:

SELECT SUM(amount) as amount, type.name as type, gamemode_statistics.Name as playerName 
FROM gamemode_statistics INNER JOIN type ON gamemode_statistics.type_id = type.id 
GROUP BY gamemode_statistics.type_id, playerName

我真的不知道如何做到这一点,我尝试了各种方法,但没有一个解决我的问题。也许我只是错误地配置了我的表?

4 个答案:

答案 0 :(得分:1)

您正在寻找一个数据透视查询,MySQL不直接支持它们。对于一个简单的3列结果,它不是太糟糕,但这不能作为n的通用解决方案 - 方式任意列:

SELECT
    SUM(IF type='KILL', amount, 0) AS KILL,
    SUM(IF type='DEATH', amount, 0) AS DEATH
    etc..
FROM ...

答案 1 :(得分:1)

如果这些是您想要显示为列的唯一三个值,则可以执行此操作,这将为您提供类型计数

SELECT SUM(amount) as amount, 
SUM(`type`='KILL') AS `KILL`,
SUM(`type`='DEATH') AS `DEATH`,
SUM(`type`='WIN') AS `WIN`,
 gamemode_statistics.Name as playerName 
FROM gamemode_statistics 
INNER JOIN type ON gamemode_statistics.type_id = type.id 
GROUP BY gamemode_statistics.type_id, playerName

答案 2 :(得分:1)

SELECT
    ISNULL(SUM(CASE WHEN type='KILL'THEN amount ELSE 0 END),0) AS KILL,
    ISNULL(SUM(CASE WHEN type='DEATH'THEN amount ELSE 0 END) AS DEATH
    etc..
FROM ...

答案 3 :(得分:0)

考虑将您的数据库放入第三范式。 http://www.andrewrollins.com/2009/08/11/database-normalization-first-second-and-third-normal-forms/

CREATE TABLE players (
  id int not null primary key auto_increment,
  name text not null,
... other player data
);

Create TABLE player_stats(
  player_id int not null primary key, -- this is a foreign key to the players table
  kills int not null default 0
  deaths not null default 0,
  wins not null default 0,
  ... other stats
);

然后查询变成

SELECT name, wins
  FROM players join player_stats on player_id = players.id
  WHERE name = 'fred';