Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple SELECT on the same field in one statement

Tags:

sql

sqlite

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!

like image 363
user1782427 Avatar asked Nov 14 '25 20:11

user1782427


1 Answers

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

like image 176
Mahmoud Gamal Avatar answered Nov 17 '25 12:11

Mahmoud Gamal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!