2016-09-01 24 views
0

我有一個PostgreSQL的說法是:如何團結同PostgreSQL的數據

(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) 

但它返回因爲UNION聲明的同一日期同一數據,

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

我怎樣才能添加這些數據值,如:

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

感謝您的幫助。

回答

2

您需要將GROUP BY移出個別查詢。類似的東西:

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; 

我也改變了UNIONUNION ALL,因爲它似乎更有意義,在這種情況下。最後,測試extract(hour from start_time) <= 24總是如此,所以它是多餘的。

+0

它工作正常,謝謝 –

1

嘗試此查詢:

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

把括號後,它的工作原理:)謝謝 –