UNION ALL之后的GROUP BY不对结果进行分组

时间:2017-06-03 09:44:30

标签: mysql group-by union-all

我在这里看了几篇关于SO的帖子,但我无法找到解决问题的方法。

我想将3个结果集合并为一个,但似乎GROUP BY不允许我对它们进行分组。相反,列被覆盖。

这是我的MYSQL查询:

SELECT spent.cid AS cid, spent.clientname AS clientname, spent.sumyearone AS sumyearone, spent.sumyeartwo AS sumyeartwo, spent.sumyearthree AS sumyearthree
FROM (
    SELECT yearone.cid AS cid, yearone.clientname AS clientname, yearone.sum AS sumyearone, 0 AS sumyeartwo, 0 AS sumyearthree
        FROM (
            ...
        ) AS yearone
    GROUP BY yearone.cid
    UNION ALL
    SELECT yeartwo.cid AS cid, yeartwo.clientname AS clientname, 0 AS sumyearone, yeartwo.sum AS sumyeartwo, 0 AS sumyearthree
       FROM (
           ...
       ) AS yeartwo
    GROUP BY yeartwo.cid
    UNION ALL
    SELECT yearthree.cid AS cid, yearthree.clientname AS clientname, 0 AS sumyearone, 0 AS sumyeartwo, yearthree.sum AS sumyearthree
        FROM (
            ...
        ) AS yearthree
    GROUP BY yearthree.cid
) AS spent
GROUP BY spent.cid
ORDER BY spent.cid DESC

如果我使用GROUP BY spent.cid运行查询,我会得到以下结果

cid    clientname    sumyearone    sumyeartwo    sumyearthree
50     Jon Doe       1083          0             0

但如果我在没有GROUP BY spent.cid的情况下运行它,我会得到三个正确的返回值:

cid    clientname    sumyearone    sumyeartwo    sumyearthree
50     Jon Doe       1083          0             0
50     Jon Doe       0             1602          0
50     Jon Doe       0             0             1367

我想要的是:

cid    clientname    sumyearone    sumyeartwo    sumyearthree
50     Jon Doe       1083          1602          1367

PS:如果我使用null代替0来进行字段声明(即null AS sumyeartwo

,我会得到类似的结果

由于

1 个答案:

答案 0 :(得分:1)

您可以使用SUMGROUP BY来获取这些数字,例如:

SELECT spent.cid AS cid, spent.clientname AS clientname, SUM(spent.sumyearone) AS sumyearone, SUM(spent.sumyeartwo) AS sumyeartwo, SUM(spent.sumyearthree) AS sumyearthree
FROM (
    SELECT yearone.cid AS cid, yearone.clientname AS clientname, yearone.sum AS sumyearone, 0 AS sumyeartwo, 0 AS sumyearthree
        FROM (
            ...
        ) AS yearone
    GROUP BY yearone.cid
    UNION ALL
    SELECT yeartwo.cid AS cid, yeartwo.clientname AS clientname, 0 AS sumyearone, yeartwo.sum AS sumyeartwo, 0 AS sumyearthree
       FROM (
           ...
       ) AS yeartwo
    GROUP BY yeartwo.cid
    UNION ALL
    SELECT yearthree.cid AS cid, yearthree.clientname AS clientname, 0 AS sumyearone, 0 AS sumyeartwo, yearthree.sum AS sumyearthree
        FROM (
            ...
        ) AS yearthree
    GROUP BY yearthree.cid
) AS spent
GROUP BY spent.cid, spent.clientname
ORDER BY spent.cid DESC