2017-09-08 69 views
0

的問題如下:比較兩個時間之間的平均purchase_amount範圍

有多高是在早上(05-11),平均購買量相比,(17-23)在晚上?

我不知道如何比較它們。

我試過這個,但我只得到一大筆錢。

select avg(purchase_amount) 
from case_data_order 
where cast (create_timestamp as time) between '05:00:00' and '11:00:00' 
or cast(create_timestamp as time) between '17:00:00' and '23:00:00'; 

我用的Postgres 9.6

回答

1

嘗試FILTER謂語去,就像這樣:

SELECT 
    count(*) AS unfiltered, 
    count(*) FILTER (WHERE i < 5) AS filtered 
FROM generate_series(1,10) AS s(i); 
unfiltered | filtered 
------------+---------- 
     10 |  4 
(1 row) 

所以在你的情況下,它會是這樣

select 
    avg(purchase_amount) FILTER (where cast (create_timestamp as time) between '05:00:00' and '11:00:00') as morning 
    , avg(purchase_amount) FILTER (where cast (create_timestamp as time) between '17:00:00' and '23:00:00') as evening 
from case_data_order 
+0

謝謝!有效!!! –

0

水木清華一樣能幫助:

SELECT 
    AVG(purchase_amount), 
    CASE 
     WHEN CAST(create_timestamp AS TIME) BETWEEN '05:00:00' AND '11:00:00' 
     THEN 'day' 
     WHEN CAST(create_timestamp AS TIME) BETWEEN '17:00:00' AND '23:00:00' 
     THEN 'night' 
    END gr 
FROM case_data_order 
WHERE CAST(create_timestamp AS TIME) BETWEEN '05:00:00' AND '11:00:00' 
     OR CAST(create_timestamp AS TIME) BETWEEN '17:00:00' AND '23:00:00' 
GROUP BY 
    CASE 
     WHEN CAST(create_timestamp AS TIME) BETWEEN '05:00:00' AND '11:00:00' 
     THEN 'day' 
     WHEN CAST(create_timestamp AS TIME) BETWEEN '17:00:00' AND '23:00:00' 
     THEN 'night' 
    END gr; 
0

如何獲得的平均值:

select d, 
     avg(case when t between '05:00:00' and '11:00:00' then purchase_amount end) as am, 
     avg(case when t between '17:00:00' and '23:00:00' then purchase_amount end) as pm 
from 
(
    select purchase_amount, 
      cast(create_timestamp as time) as t, 
      cast(create_timestamp as date) as d 
    from case_data_order 
) dt 
group by d