Postgresql: count records by time intervals

与世无争的帅哥 提交于 2021-01-28 19:31:54

问题


I am trying to use the following SQL statement with postgresql to generate some report:

WITH GRID AS (
  SELECT START_TIME, LEAD(START_TIME) OVER (ORDER BY START_TIME) AS END_TIME 
  FROM  (
    SELECT GENERATE_SERIES('2015-08-01 12:00:00', '2015-09-01 12:00:00',  INTERVAL '1 day') AS START_TIME 
    FROM   MY_TABLE
    ) x
  )
  SELECT 
    START_TIME, COUNT(MY_TABLE._ID) AS COUNT 
    FROM
      GRID 
      LEFT   JOIN MY_TABLE ON MY_TABLE.CREATED >= GRID.START_TIME AND MY_TABLE.CREATED <  GRID.END_TIME  
    WHERE MY_TABLE.COMPANY_ID = '1001'  AND MY_TABLE.CUSTOMER_ID = '1003' 
    GROUP  BY 1 ORDER  BY 1

What I expected would be like:

  • "2015-08-01 12:00:00+02"; 0
  • "2015-08-02 12:00:00+02"; 1
  • "2015-08-03 12:00:00+02"; 0
  • "2015-08-04 12:00:00+02"; 1
  • "2015-08-05 12:00:00+02"; 0
  • ....
  • "2015-08-31 12:00:00+02"; 0

but the actual result is:

  • "2015-08-02 12:00:00+02";1
  • "2015-08-04 12:00:00+02";1

it simply skips the records with 0 count.

if I don't specify the where clause (condition part), I could get the expected result.

can anyone help me out?

thank you!


回答1:


Folllowing query seems do what you want:

WITH GRID AS
(
  SELECT 
    START_TIME,
    LEAD(START_TIME) OVER (ORDER BY START_TIME) AS END_TIME
  FROM
  (
    SELECT 
      GENERATE_SERIES('2015-08-01 12:00:00', '2015-09-01 12:00:00', INTERVAL '1 day') AS START_TIME
    FROM MY_TABLE 
  ) x 
)
SELECT 
  START_TIME,
  COUNT(MY_TABLE._ID) AS COUNT
FROM GRID
LEFT JOIN MY_TABLE ON 
  MY_TABLE.CREATED >= GRID.START_TIME AND 
  MY_TABLE.CREATED < GRID.END_TIME AND 
  MY_TABLE.COMPANY_ID = '1001' AND 
  MY_TABLE.CUSTOMER_ID = '1003'
GROUP BY 1
ORDER BY 1


来源:https://stackoverflow.com/questions/31997433/postgresql-count-records-by-time-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!