I have a database with a lot of data in it already that is seperated by state, year, and quarter. So the DB layout is something like this:
jurisdiction | total_miles | quarter | year |
---|---|---|---|
AL | 300 | 3 | 2022 |
AL | 500 | 3 | 2022 |
AL | 200 | 4 | 2022 |
AL | 100 | 1 | 2023 |
AL | 50 | 2 | 2023 |
These two separate queries work by themselves to get the total from the quarters 3 and 4 from 2022 and quarters 1 and 2 from 2023:
SELECT sum(total_miles) FROM db_table WHERE quarter >= 3 AND year = '2022' AND jurisdiction = 'AL';
SELECT sum(total_miles) FROM db_table WHERE quarter <= 2 AND year = '2023' AND jurisdiction = 'AL';
I tried to combine the two queries by using the query
SELECT sum(total_miles) FROM db_table WHERE (quarter >= 3 AND year = '2022') AND (quarter <= 2 AND year = '2023') AND jurisdiction = 'AL'
But I get a NULL return value for sum(total_miles). I tried using variables to try and add up the values and it gives me a different number than the actual total for the state. Is there a way to correctly write the query so that it sums up the total miles from quarters 3 and 4 of 2022 and quarters 1 and 2 of 2023?
2
Answers
If you’d like the combined mileage for both periods, then here’s how to do it:
Result:
If, instead, you’d like the miles for each period separately, but using a single query, then here’s how to do that:
Here’s the result:
NOTE: These queries use tabs and newlines that may causes issues for you. If that’s the case, try starting your mysql client with the
--disable-auto-rehash
option, like this:Alternatively, you can strip the whitespace from the queries instead.
As stated in the comments, you can fix your query by making it
Alternatively, since the column names match, you could use
UNION
Like Andy’s answer, this will give you both numbers in one result (instead of the total), but with the data in rows instead of columns