问题
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