按小时间隔计算

时间:2018-03-21 15:34:57

标签: sql database postgresql

我在postgresql中编写了一个SQL查询,工作正常,它可以让我获得每小时每位员工完成的工作数量

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;

如果每个间隔时间都有一个人员,那么这是完美的,但是当一个小时没有员工的数据时,它会被省略。如何让它工作,以便结果包含每个间隔的行,如果员工在那个时间没有工作,则将值字段设置为零。

1 个答案:

答案 0 :(得分:2)

您可以使用generate_series函数生成小时系列:

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

然后用它填补小时差距:

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)