不止一个具有不同条件的AVG色谱柱

时间:2016-02-16 06:31:09

标签: sql postgresql

我有一张表格如下:

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年的AVG值。意思是如果今天是2016年那么AVG将在2015,2014,2013。

基本上这可以通过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)? 它应该没有WHERE。

类似的东西:

Select avg(with condition) as a, avg(with condition) as b, avg(with condition) as c
from tab

2 个答案:

答案 0 :(得分:3)

您可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)

答案 1 :(得分:1)

select 
    avg(case when year = date_part('year', NOW()) then value end) as avg_2016,
    avg(case when year = ((date_part('year', NOW())) - 1 ) then value end) as avg_2015,
    avg(case when year = ((date_part('year', NOW())) - 2 ) then value end) as avg_2014,
     avg(case when year = ((date_part('year', NOW())) - 3 ) then value end) as avg_2013
from tab