是否计算postgresql中的日期差异?

hec6srdp  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(1)|浏览(112)

这是我的数据集。

emp_id|emp_name|work_start_date|work_end_date|days_worked_on|
------+--------+---------------+-------------+--------------+
     1|A       |     2023-03-01|   2023-03-03|             2|
     2|B       |     2023-03-04|   2023-03-04|             0|

实际上,我想计算多少天的人工作。所以我计算的基础上,下面的查询。

select 
    emp_id
    ,emp_name
    ,work_start_date
    ,work_end_date   
    ,work_end_date - work_start_date as days_worked_on
from demo.stackquestions;

理想情况下,人员A在03/01、03/02和03/03工作。总共3天。但在计算work_end_date - work_start_date时,给出了2天。(技术上是的。但实际上答案是错误的。)为了计算正确的天数,我是否需要在最后加1(+1)?

work_end_date - work_start_date +1 as days_worked_on

这是正确的做法吗?请分享你的想法。

i7uq4tfw

i7uq4tfw1#

使用generate_series获取日期范围内的日期计数。这里假设2023-03-04, 2023-03-04等于一个工作日。

CREATE TABLE stackquestions (
    emp_id integer,
    emp_name varchar,
    work_start_date date,
    work_end_date date
);

INSERT INTO stackquestions
    VALUES (1, 'A', '2023-03-01', '2023-03-03');

INSERT INTO stackquestions
    VALUES (2, 'B', '2023-03-04', '2023-03-04');

WITH date_ct AS (
    SELECT
        sq.emp_id,
        count(a) AS days_worked_on
    FROM
        stackquestions AS sq,
        generate_series(work_start_date, work_end_date, '1 day') AS t (a)
    GROUP BY
        emp_id
)
SELECT
    stackquestions.*,
    date_ct.days_worked_on
FROM
    stackquestions
    JOIN date_ct ON stackquestions.emp_id = date_ct.emp_id;

emp_id | emp_name | work_start_date | work_end_date | days_worked_on 
--------+----------+-----------------+---------------+----------------
      1 | A        | 03/01/2023      | 03/03/2023    |              3
      2 | B        | 03/04/2023      | 03/04/2023    |              1

相关问题