简体   繁体   中英

Comparing 2 query result in a query PostgreSQL

I'm wondering if it's possible to compare 2 query result into one in PostgreSQL. For example: I have this data on the whole month of March then i have another data for the whole month of april.

This query is the one I'm using to get the data on the month of March:

    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

Then this is the one I'm using to get the data on the month of April:

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

Is it possible for me to combine them to one data so I can display the result on both month? For example:

Month     percentage
March      100%
February   85%

Yes, use conditional aggregation:

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';

Note that you should not be aggregating by date, because the averages you want to take span multiple dates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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