1

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 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Great! Thanks a lot! it works like a charm. so it seems if I include the condition in where clause, it won't include these items with 0 count.
Yep. That's how where conditions work - everything in the final output must meets them, whereas left join conditions add data to the output but doesn't cause row to be hidden from output if no data found.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.