Postgresql:按时间间隔计算记录

时间:2015-08-13 20:04:50

标签: postgresql join count report

我正在尝试使用以下SQL语句和postgresql来生成一些报告:

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

我的期望是什么:

  • “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

但实际结果是:

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

它只是跳过0计数的记录。

如果我没有指定where子句(条件部分),我可以得到预期的结果。

任何人都可以帮助我吗?

谢谢你!

1 个答案:

答案 0 :(得分:0)

以下查询似乎符合您的要求:

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