简体   繁体   English

PostgreSQL 多列输出使用 where 子句

[英]PostgreSQL multiple column outputs using where clause

I would like to find the average of a column for 2 time periods but I'm unsure how to display both in single query.我想找到 2 个时间段内一列的平均值,但我不确定如何在单个查询中显示这两个时间段。 I know the below won't work but I'm looking for the proper syntax:我知道以下不起作用,但我正在寻找正确的语法:

SELECT
AVG(amount) AS avg_amt
FROM table
WHERE day >= date('2019-05-05') AND day<= date('2019-07-04'),
AVG(amount) AS avg_amt2
WHERE day >= date('2019-07-05') AND day<= date('2019-09-04')

You can use the FILTER clause to aggregate functions:您可以使用FILTER子句来聚合函数:

SELECT
    AVG(amount) FILTER(WHERE day >= date '2019-05-05' AND day <= date '2019-07-04') AS avg_amt1,
    AVG(amount) FILTER(WHERE day >= date '2019-07-05' AND day <= date '2019-09-04') AS avg_amt2
FROM table

We can optimize the query a little with a WHERE clause:我们可以使用WHERE子句稍微优化查询:

SELECT
    AVG(amount) FILTER(WHERE day <= date '2019-07-04') AS avg_amt1,
    AVG(amount) FILTER(WHERE day >= date '2019-07-05') AS avg_amt2
FROM table
WHERE day >= date '2019-05-05' AND day <= date '2019-09-04'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM