比较两个时间范围之间的平均purchase_amount

时间:2017-09-08 09:26:27

标签: sql postgresql

问题如下:

早上(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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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