2016-09-01 4 views
0

Ich habe eine postgresql Aussage vereinigen, das ist:Wie Same PostgreSQL Data

(select cast(start_time as date) as time , SUM(count) as count 
from tbl_product 
where (cast(start_time as date) >= '2016-08-30 23:00:00' and cast(start_time as date) <= '2016-09-01 20:00:00') 
and (extract(hour from start_time) >= 23 and extract(hour from start_time) <= 24)  
group by time order by time limit 5) 

UNION (select cast(start_time as date) as time , SUM(count) as count 
from tbl_product 
where (cast(start_time as date) >= '2016-08-31 23:00:00' and cast(start_time as date) <= '2016-09-01 20:00:00') 
and (extract(hour from start_time) >= 0 and extract(hour from start_time) < 20)  
group by time order by time limit 5) 

Aber es gibt die gleichen Daten für das gleiche Datum, wegen einer UNION Aussage

time   count 
date   numeric 
"2016-08-31" 543595 
"2016-08-31" 3666277 
"2016-09-01" 3365093 

Wie kann ich addiere diese Datenwerte wie:

time   count 
date   numeric 
"2016-08-31" 4209872 
"2016-09-01" 3365093 

Danke für die Hilfe.

Antwort

2

Sie müssen die GROUP BY aus den einzelnen Abfragen verschieben. So etwas Ähnliches:

SELECT time, SUM(count) as count FROM (
    (select cast(start_time as date) as time , count 
    from tbl_product 
    where (cast(start_time as date) >= '2016-08-30 23:00:00' and cast(start_time as date) <= '2016-09-01 20:00:00') 
    and (extract(hour from start_time) >= 23)) 
     UNION ALL 
    (select cast(start_time as date) as time , count 
    from tbl_product 
    where (cast(start_time as date) >= '2016-08-31 23:00:00' and cast(start_time as date) <= '2016-09-01 20:00:00') 
    and (extract(hour from start_time) >= 0 and extract(hour from start_time) < 20)) 
    ) AS t 
GROUP BY time ORDER by time; 

Ich habe änderte auch die UNION zu einem UNION ALL, weil es scheint, mehr Sinn in diesem Fall zu machen. Schließlich ist der Test extract(hour from start_time) <= 24 immer wahr, also ist es überflüssig.

+0

Es funktioniert gut, Dank –

1

versuchen, diese Abfrage:

select 
exe.time_, 
sum(exe.count_) 
from 
(
    select cast(start_time as date) as time_ , SUM(count) as count_ 
    from tbl_product 
    where (cast(start_time as date) >= '2016-08-30 23:00:00' and cast(start_time as date) <= '2016-09-01 20:00:00') 
    and (extract(hour from start_time) >= 23 and extract(hour from start_time) <= 24)  
    group by time order by time limit 5 
    UNION 
    select cast(start_time as date) as time_, SUM(count) as count_ 
    from tbl_product 
    where (cast(start_time as date) >= '2016-08-31 23:00:00' and cast(start_time as date) <= '2016-09-01 20:00:00') 
    and (extract(hour from start_time) >= 0 and extract(hour from start_time) < 20)  
    group by time order by time limit 5 
) exe 
group by exe.time_ 
+0

nach Klammer setzen, es funktioniert :) Danke –