gpt4 book ai didi

sql - 具有不同条件的多个 AVG 列

转载 作者:行者123 更新时间:2023-11-29 12:36:40 25 4
gpt4 key购买 nike

我有一个表格如下:

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

最佳答案

您可以group by year 并在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com