I got the following table:
**stats**
id INT FK
day INT
value INT
I would like to create an SQL query that will sum the values in value column in the last day, last week and last month, in one statement.
So Far i got this:
select sum(value) from stats as A where A.day > now() - 1
union
select sum(value) from stats as B where B.day > now() - 7
union
select sum(value) from stats as C where C.day > now() - 30
This returns just the first sum(value), i was expecting 3 values to return.
Running: select sum(value) from stats as A where A.day > now() - X ( Where x = 1/7/30) in different queries works as it should.
What's wrong with the query? Thanks!
UNION is implicit distinct. Use UNION ALL instead like so:
SELECT 'last day' ItemType, sum(value) FROM stats as A WHERE A.day > now() - 1
UNION ALL
SELECT 'last week', SUM(value) FROM stats as B WHERE B.day > now() - 7
UNION ALL
SELECT 'last month', SUM(value) FROM stats as C WHERE C.day > now() - 30
Note that: I added a new column ItemType to indicate what is the type of the sum value whether it is last day, last week or last month
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With