比较Postgres中两个日期范围的计数

时间:2018-08-15 09:21:14

标签: sql postgresql date-range postgresql-9.6

我试图比较单个PostgreSQL 9.6.5表中的两个日期范围。这两个日期范围的长度彼此相同,分别为本周上周本月上个月过去180天之前180天。该表捕获了客户互动,每行记录了一次互动-日期,开始时间,停止时间,位置等。

我设法为单个日期范围构造了SQL。

SELECT 
  to_char(date, 'day') as day,
  extract(dow from date) as dow,
  count(*) AS curr_count
FROM schema.table
WHERE (date between :date_start AND :date_stop) 
GROUP BY day, dow
ORDER BY dow ASC

开始日期设置为'2018-08-08',将停止日期设置为'2018-08-15',我得到以下记录集:

Array ( 
 [0] => Array ( [day] => monday [0] => monday [dow] => 1 [1] => 1 [curr_count] => 78 [2] => 78 ) 
 [1] => Array ( [day] => tuesday [0] => tuesday [dow] => 2 [1] => 2 [curr_count] => 75 [2] => 75 ) 
 [2] => Array ( [day] => wednesday [0] => wednesday [dow] => 3 [1] => 3 [curr_count] => 62 [2] => 62 ) 
 [3] => Array ( [day] => thursday [0] => thursday [dow] => 4 [1] => 4 [curr_count] => 68 [2] => 68 ) 
 [4] => Array ( [day] => friday [0] => friday [dow] => 5 [1] => 5 [curr_count] => 81 [2] => 81 ) 
 [5] => Array ( [day] => saturday [0] => saturday [dow] => 6 [1] => 6 [curr_count] => 3 [2] => 3 ) 
)

我可以很容易地计算上一个时期(2018-08-01至2018-08-07)的日期,但是我不知道如何将这些日期添加到SQL中以获得所需的结果。我想要的最终结果是:

array (
 array (day, dow, curr_count, prev_count)
 array (day, dow, curr_count, prev_count)
 array (day, dow, curr_count, prev_count)
 array (day, dow, curr_count, prev_count)
)

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

让我假设您有两组参数,它们定义了您要比较的两个时间段:

with p1 as (
      select date::date as date,
             extract(dow from date) as dow,
             count(*) AS curr_count,
             row_number() over (order by date::date) as seqnum
      from schema.table
      where date between :date_start_1 and :date_stop_1
      group by date::date
     ),
     p2 as (
      select date::date as date,
             extract(dow from date) as dow,
             count(*) AS curr_count,
             row_number() over (order by date::date) as seqnum
      from schema.table
      where date between :date_start_2 and :date_stop_2
      group by date::date
     )
select p1.*, p2.curr_count as prev_count
from p1 join
     p2
     on p2.seqnum = p1.seqnum;

我将第一列更改为一个明确的日期。我怀疑您是否真的只希望每月的某天和一周中的某天确定结果集(当然,如果您确实打算这样做,就可以调整逻辑)。

相关问题