我想知道是否可以在PostgreSQL中将2个查询结果比较为1个。 例如:我有整个3月的数据,然后又有4月的整个月的数据。
此查询是我用来获取3月份数据的查询:
SELECT availability_date, ROUND(AVG(availability_percentage),2)
FROM dashboard.availability
WHERE availability_date BETWEEN '2020-03-01' AND '2020-04-01'
GROUP BY availability_date
ORDER BY availability_date ASC
然后这就是我用来获取4月份数据的那个:
SELECT availability_date, ROUND(AVG(availability_percentage),2)
FROM dashboard.availability
WHERE availability_date BETWEEN '2020-04-01' AND '2020-05-01'
GROUP BY availability_date
ORDER BY availability_date ASC
是否可以将它们合并为一个数据,以便我可以在两个月显示结果? 例如:
Month percentage
March 100%
February 85%
答案 0 :(得分:1)
是的,请使用条件聚合:
SELECT
ROUND(AVG(availability_percentage)
FILTER (WHERE availability_date BETWEEN '2020-03-01' AND '2020-04-01') , 2) AS avg_march,
ROUND(AVG(availability_percentage)
FILTER (WHERE availability_date BETWEEN '2020-04-01' AND '2020-05-01'), 2) AS avg_april
FROM dashboard.availability
WHERE availability_date BETWEEN '2020-03-01' AND '2020-05-01';
请注意,您应该不按日期进行汇总,因为要获取的平均值跨越多个日期。