1
SELECT CASE WHEN date_part('hour',created_at) BETWEEN 3 AND 15 THEN '9am-3pm' 
            WHEN date_part('hour',created_at) BETWEEN 15 AND 18 THEN '3pm-6pm' END "time window",COUNT(*) FROM tickets where created_at < now()
GROUP BY  CASE WHEN date_part('hour',created_at) BETWEEN 3 AND 15 THEN '9am-3pm' WHEN date_part('hour',created_at) BETWEEN 15 AND 18 THEN '3pm-6pm' END;

 time window | count 
-------------+-------
             |     6
 9am-3pm     |    69

is it possible to filter it by date along with time so that my result set will looks like

Date        | time window | count 
------------+-------------+-------
12-01-2020  |      9am-3pm|     6
12-01-2020  |      3pm-6pm|    69
13-01-2020  |      9am-3pm|    12
13-01-2020  |      3pm-6pm|    14

2 Answers 2

1

We can handle this requirement using a calendar table approach:

WITH dates AS (
    SELECT '12-01-2020' AS created_at UNION ALL
    SELECT '13-01-2020'
),
tw AS (
    SELECT '9am-3pm' AS "time window" UNION ALL
    SELECT '3pm-6pm'
),
cte AS (
    SELECT
        created_at::date AS created_at,
        CASE WHEN DATE_PART('hour', created_at) BETWEEN 3 AND 15 THEN '9am-3pm'
             WHEN DATE_PART('hour', created_at) BETWEEN 15 AND 18 THEN '3pm-6pm' END "time window",
        COUNT(*) AS cnt
    FROM tickets
    WHERE created_at < NOW()
    GROUP BY 1, 2
)

SELECT
    d.created_at,
    tw."time window",
    COALESCE(t.cnt, 0) AS count
FROM dates d
CROSS JOIN tw
LEFT JOIN cte t
    ON d.created_at = t.created_at AND tw."time window" = t."time window"
ORDER BY
    d.dt,
    tw."time window";
Sign up to request clarification or add additional context in comments.

1 Comment

looking for same query as return by me : ``` SELECT CASE WHEN date_part('hour',created_at) BETWEEN 3 AND 15 THEN '9am-3pm' WHEN date_part('hour',created_at) BETWEEN 15 AND 18 THEN '3pm-6pm' END "time window",COUNT(*) FROM tickets where created_at < now() GROUP BY CASE WHEN date_part('hour',created_at) BETWEEN 3 AND 15 THEN '9am-3pm' WHEN date_part('hour',created_at) BETWEEN 15 AND 18 THEN '3pm-6pm' END; ``` it is fine if there is no date column main thing is time window and count
0

You are actually asking two questions:

  • The "empty space" (really an SQL NULL) is there because there are dates that do not fall within any of the time ranges. You can exclude them with an additional WHERE condition.

  • To get the date part as well, add

    CAST (created_at AS date)
    

    to the SELECT list and the GROUP BY ckause.

1 Comment

Note that this approach might result in missing dates/slots should the OP's table have no data there.

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.