0

i have written an SQL query in postgresql that works fine it gets me the number of work done per employee for every hour

SELECT COUNT(work_done) AS count, EXTRACT(hour from start_time) AS hour FROM c_call WHERE start_time >= '2018-10-13 00:00:00' GROUP BY employee_id; 

it's perfect if an emplyee was actif ine every interval hour but when an hour has no data for an employee it is omitted . how can make it work so that the result contains a row for each interval with the value field set to zero if the employee didnt work at that hour.

10
  • 2
    A row with 0 for every non-worked hour? That will be a lot of rows. Commented Mar 21, 2018 at 15:38
  • yes but i can then process that data elsewhere ( i only need the data for the day so it wont be too much rows ) Commented Mar 21, 2018 at 15:39
  • What exactly is the point of such a return value? That's not something that's particularly easy to do in SQL, and honestly, I'm struggling to think of why you'd want to do so here as opposed to application logic. Commented Mar 21, 2018 at 15:39
  • it's because i need to display this data in a google table chart and for the google table chart i need to specify each column value ( the google table chart is drawn dynamically ) so it would be much easier to send data like that Commented Mar 21, 2018 at 15:41
  • Have a help table (or recursive cte) with a row for each hour. Right join that table. Commented Mar 21, 2018 at 15:42

1 Answer 1

2

You can generate a hour series using generate_series function:

SELECT * FROM generate_series(0, 23) AS foo(bar) 

And then use it to fill the hour gaps:

WITH employee_call AS ( SELECT COUNT(work_done) AS count, EXTRACT(hour from start_time) AS hour_fraction FROM c_call WHERE start_time >= '2018-10-13 00:00:00' GROUP BY employee_id ), hour_series (hour_fraction) AS ( SELECT generate_series(0, 23) ) SELECT COALESCE(c.count, 0) AS count, COALESCE(c.hour_fraction, h.hour_fraction) AS hour_fraction FROM hour_series h LEFT JOIN employee_call c ON (c.hour_fraction = h.hour_fraction) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.