Domanda

query 1:

SELECT SUM(duration) FROM table_name WHERE timestart >= past24hours

query 2:

SELECT SUM(duration) FROM table_name WHERE timestart >= past7days

Hi all, i want to combined above two query and get sum in query. Any way to do this?

Currently i have 2 more query in addition to above for past 30 days and 365 days.

Anyone please help.

È stato utile?

Soluzione

You can use union

like

SELECT SUM(duration) FROM table_name WHERE timestart >= past24hours
UNION
SELECT SUM(duration) FROM table_name WHERE timestart >= past7days

Altri suggerimenti

SELECT SUM(duration), 1 FROM table_name WHERE timestart >= '$date' - INTERVAL 1 DAY
UNION
SELECT SUM(duration), 2 FROM table_name WHERE timestart BETWEEN '$date' - INTERVAL 7 DAY AND '$date' - INTERVAL 1 DAY

this way you wont get rows with timestart in last 24 hours twice

One way is to get all sums with different alias is as

select
t.sum1,t.sum2
from(
select 
 sum(case when timestart >= past24hours then duration END) as sum1,
 sum(case when timestart >= past7days then duration END) as sum2  
 from table_name
)t

You can add any number of sums within the query and give an alias name and add them in the select list so that they could be parsed later with your server side script.

With UNION it will return the same column/alias. When you have same sum value in UNION it will get only one and to get rid of it you can use UNION ALL

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top