我有一个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
感谢您的帮助。
答案 0 :(得分: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;
我还将UNION
更改为UNION ALL
,因为在这种情况下似乎更有意义。最后,测试extract(hour from start_time) <= 24
始终为真,因此它是多余的。
答案 1 :(得分: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_