在一个查询中计算许多项

时间:2011-11-28 18:38:14

标签: mysql count

这就是我现在所得到的:

SELECT `p`.`name`, SUM(`count`) FROM `player_items`
LEFT JOIN `players` `p` ON (`p`.`id` = `player_items`.`player_id`)
WHERE `itemtype` IN (2148, 2152, 2160) GROUP by `player_id`, `itemtype`

它撤销玩家姓名和ID为2148,2152,2160的项目类型的SUM

我需要重写此查询,以便为每个ID选择项目计数,这就是结果的样子:

| NAME   | ITEM | COUNT |
| Player | 2148 | 10    |
| Player | 2152 | 760   |
| Player | 2160 | 0     |

|  NAME   | ITEM | COUNT |
| Player1 | 2148 | 890   |
| Player1 | 2152 | 5560  |
| Player1 | 2160 | 2584  |

结构:

Table name = player_items
ITEM ID(2148, 2152, 2160) - itemtype
ITEM COUNT - count.

请注意,每个商品ID都可以包含其他“COUNT”值,例如,对于player_items表中的一个玩家,它将如下所示:

PLAYER_NAME | 2148 | 10
PLAYER_NAME | 2148 | 4
PLAYER_NAME | 2148 | 4
PLAYER_NAME | 2152 | 60
PLAYER_NAME | 2152 | 20
PLAYER_NAME | 2160 | 100

如果你没有得到任何东西,请告诉我。

1 个答案:

答案 0 :(得分:0)

我不太清楚你的问题是什么。你不想只返回项目ID(称为itemtype)??

SELECT 
    `p`.`name` AS `Name`,
    `i`.`itemtype` AS `Item`,
    SUM(`i`.`count`) AS `Count`
FROM
    `player_items` AS `i`
LEFT JOIN 
    `players` AS `p`
    ON
        (`p`.`id` = `i`.`player_id`)
WHERE 
    `i`.`itemtype` IN (2148, 2152, 2160) 
GROUP BY
    `i`.`player_id`,
    `i`.`itemtype`

这是一个社区维基,因此可以根据需要进行更正。