MySQL:如何从一个GROUP BY级别中选择一个值并在所有级别中进行广播

时间:2019-07-05 14:53:18

标签: mysql grouping

我有一个像这样的MYSQL表

person giftaid postcode year amount
A      1       NULL     2010     10
A      0       XY123    2010     15
A      0       NULL     2011     10
A      0       NULL     2011     20
B      0       NULL     2010     20
B      0       NULL     2010      1
B      0       NULL     2011     30
C      1       NULL     2010     50
C      1       AB345    2011     80

我想对每个人每年的总金额求和,但是要取任何一年中该人的礼物和邮政编码值。即我需要

person ever_giftaided any_postcode year sum
A      1              XY123        2010 25
A      1              XY123        2011 30
B      0              NULL         2010 21
B      0              NULL         2011 30
C      1              AB345        2010 50
C      1              AB345        2011 80

请注意,尽管A人在2011年不同意礼物赠与,但由于他们在2010年同意,我很高兴在ever_giftaided列中填写所有年份的1,并接受任何非null邮政编码。

如果我做一个简单的GROUP BY person, year,并使用MAX(giftaid) AS ever_giftaided, MAX(postcode) AS any_postcode,则在第二行中,人A的0得到一个ever_giftaided,而{{1 }},因为group by子句不会在any_postcode的分组之间传递信息,而是在personperson的组合分组之间传递信息。我可以简单地year,但是然后我没有按年份细分金额。那我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

加入两个查询。一组按person分组,另一组按person, year分组。

SELECT t1.person, t1.ever_giftaided, t1.any_postcode, t2.year, t2.sum
FROM (
    SELECT person, MAX(giftaided) AS ever_giftaided, MAX(postcode) AS any_postcode
    FROM yourTable
    GROUP BY person) AS t1
JOIN (
    SELECT person, year, SUM(amount) AS sum
    FROM yourTable
    GROUP BY person, year) AS t2 ON t1.person = t2.person

您还可以在主查询中进行以下分组之一:

SELECT t1.person, MAX(giftaided) AS ever_giftaided, MAX(postcode) AS any_postcode,
         t2.year, t2.sum
FROM yourTable AS t1
JOIN (
    SELECT person, year, SUM(amount) AS sum
    FROM yourTable
    GROUP BY person, year) AS t2 ON t1.person = t2.person
GROUP BY t1.person