I have 2 selects that just get the SUM of IDs and are grouped by month.. I would like to have them only on 1 SELECT – side by side…
SELECT MONTH(data) AS month, COUNT(id) AS TOTAL
FROM numeracao
WHERE data BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY MONTH(DATA);
the 2nd select:
SELECT MONTH(dia) AS month, COUNT(id) AS TOTAL
FROM revisoes
WHERE dia BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY MONTH(dia)
The rewsult was to be expected somethinig like this:
month | NUM | REV |
---|---|---|
1 | 22 | 4 |
2 | 52 | 23 |
… | … | … |
where:
- month is from 1 to 12
- NUM is the sum of query 1 on table numeracao
- REV is the sum of query 2 on table revisoes
3
Answers
You can apply the inner join on the results of the aggregations to make counts appear on the same row for each month.
Computing the aggregation after the inner join would bring to duplicate rows and incorrect output, given than the two tables most likely have a n-to-n association.
If you’re not ensured to have at least one value for all months on both tables, you should have a month calendar table and use left join instead.
I wouldn’t recommend this one anyways if your problem gets solved with the former query.
You can do this by using union and then an outer aggregation: