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



我有一个这样的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 年不同意 giftaid,因为他们在 2010 年同意,但我很高兴在所有年份都用 1 填写ever_giftaided列,并获取任何非空邮政编码。

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

联接两个查询。一个按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

相关内容

  • 没有找到相关文章

最新更新