我有一张桌子如下:
id year value
1 2012 10
2 2013 7
3 2013 7
4 2014 8
5 2014 10
6 2015 6
7 2011 12
我需要写一个查询,给出从今天起过去4年的平均值。也就是说,如果今天是2016年,那么平均值是201520142013年。
基本上这可以通过3个查询完成:
Select avg(value) as a
from tab
where year=2015
和
Select avg(value) as b
from tab
where year=2014
和
Select avg(value) as c
from tab
where year=2013
基于给定值的结果应为:
2013 7
2014 9
2015 6
既然他们都在同一张桌子上。。。如何在一个查询(postgresql)中做到这一点?
应该没有地方。
类似于:
Select avg(with condition) as a, avg(with condition) as b, avg(with condition) as c
from tab
最佳答案
您可以group by
年,并在where
条款中压缩到所需的年数
select avg(value), year
from tab
where year in (2013,2014,2015)
group by year
上面的查询将为您提供3个单独的行。如果您喜欢单行,那么可以使用条件聚合而不是
group by
select
avg(case when year = 2013 then value end) as avg_2013,
avg(case when year = 2014 then value end) as avg_2014,
avg(case when year = 2015 then value end) as avg_2015,
from tab
where year in (2013,2014,2015)
关于sql - 一个以上具有不同条件的AVG色谱柱,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35425340/