按一个值和其他值的平均值分组,其中其他值成为列

时间:2020-12-28 15:15:21

标签: mysql sql pivot average aggregate-functions

我有这张桌子。

country |   date     | cost
--------|------------|------
UK      | 2020-02-14 | 3.15
USA     | 2020-02-15 | 6.52
USA     | 2020-06-15 | 4.71
USA     | 2020-06-17 | 2.23
UK      | 2020-11-01 | 7.99
USA     | 2020-11-05 | 5.55
UK      | 2020-11-09 | 3.33

我想制作一个 query,它给我这样的结果:

country | AVG-2020-02 | AVG-2020-06 | AVG-2020-11
--------|-------------|-------------|-------------
UK      | 3.15        | 0/null      | 5.66
USA     | 6.52        | 3.47        | 5.55

我想按国家/地区对所有行进行分组,并根据月份计算平均成本。其中月份也成为一列。

现在我有这个:

SELECT tbname.country, AVG(tbname.cost)
FROM tbname
WHERE tbname.date LIKE "2020-%"
GROUP BY tbname.country

但是这个查询给了我一列,其中包含按国家/地区分组的平均行数。

可以进行一个查询,它可以给我想要的结果?以及如何?

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select country,
    avg(case when month(date) = 1 then cost end) as avg_jan,
    avg(case when month(date) = 2 then cost end) as avg_feb,
    ...
from tbname
where date >= '2020-01-01'
group by country

avg() 中进行直接过滤可能更有效:

select country,
    avg(case when date < '2020-02-01' then cost end) as avg_jan,
    avg(case when date >= '2020-02-01' and date < '2020-03-01' then cost end) as avg_feb,
    ...
from tbname
where date >= '2020-01-01'
group by country