有什么办法可以将Union All列中的两个合并

时间:2018-12-27 20:42:41

标签: sql count union-all

我正在制作《英雄联盟》 Api,我在数据库中有这样的项目 database 我有这样的sql代码来检查ppl在游戏中购买这些物品的次数

SELECT
Items.Item,
count(Items.Item) as repeats
FROM 
(
    SELECT Item0 AS Item FROM playergame
    UNION ALL
    SELECT Item1 AS Item FROM playergame
    UNION ALL
    SELECT Item2 AS Item FROM playergame
    UNION ALL
    SELECT Item3 AS Item FROM playergame
    UNION ALL
    SELECT Item4 AS Item FROM playergame
    UNION ALL
    SELECT Item5 AS Item FROM playergame
    UNION ALL
    SELECT Item6 AS Item FROM playergame
) AS Items 
GROUP BY
Items.Item  
ORDER BY `repeats`

这段代码给了我类似的东西

result of sql

我想在右侧添加另一个带有重复的表,但是这次添加到代码WHERE中,所以我编写了以下代码:

SELECT
Items.Item,
count(Items.Item) as repeats,
count(ItemW.ItemW) as Wrepeats
FROM 
(
    SELECT Item0 AS Item FROM playergame
    UNION ALL
    SELECT Item1 AS Item FROM playergame
    UNION ALL
    SELECT Item2 AS Item FROM playergame
    UNION ALL
    SELECT Item3 AS Item FROM playergame
    UNION ALL
    SELECT Item4 AS Item FROM playergame
    UNION ALL
    SELECT Item5 AS Item FROM playergame
    UNION ALL
    SELECT Item6 AS Item FROM playergame
) AS Items 
INNER JOIN 
(
    SELECT Item0 AS ItemW FROM playergame
    UNION ALL
    SELECT Item1 AS ItemW FROM playergame WHERE Win = 1
    UNION ALL
    SELECT Item2 AS ItemW FROM playergame WHERE Win = 1
    UNION ALL
    SELECT Item3 AS ItemW FROM playergame WHERE Win = 1
    UNION ALL
    SELECT Item4 AS ItemW FROM playergame WHERE Win = 1
    UNION ALL
    SELECT Item5 AS ItemW FROM playergame WHERE Win = 1
    UNION ALL
    SELECT Item6 AS ItemW FROM playergame WHERE Win = 1
)AS ItemW
ON Items.Item = ItemW.ItemW
GROUP BY
Items.Item

从这个SQL我得到了这个结果 second result of sql

1 个答案:

答案 0 :(得分:1)

我想你想要

SELECT i.Item, COUNT(*) as repeats,
       SUM(CASE WHEN Win = 1 THEN 1 ELSE 0 END) as Wins
FROM (SELECT Item0 AS Item, Win FROM playergame
      UNION ALL
      SELECT Item1 AS Item, Win FROM playergame
      UNION ALL
      SELECT Item2 AS Item, Win FROM playergame
      UNION ALL
      SELECT Item3 AS Item, Win FROM playergame
      UNION ALL
      SELECT Item4 AS Item, Win FROM playergame
      UNION ALL
      SELECT Item5 AS Item, Win FROM playergame
      UNION ALL
      SELECT Item6 AS Item, Win FROM playergame
     ) i 
GROUP BY i.Item  
ORDER BY `repeats`;

也就是说,您应该修复数据结构。您应该有另一个名为playergameItems的表,每个“玩家游戏”有一行,而每个item有一行。