查询为两个日期之间的日期系列提供重复的薪水列
Query giving repeated salary columns for date series between two dates
嗨,我想要日期和相应的值在 postgres 中是唯一的
我有一个 table,其中给出了开始日期、结束日期和薪水。我想计算日期系列和该期间的工资。 table 就像
Salary Startdate Enddate
1000 "2015-09-28" "2015-09-30"
我希望查询结果像
dates salary
2015-09-28 1000
2015-09-29
2015-09-30
我使用的查询是
select salary, generate_series("startdate", "enddate", '1 day'::interval)::date as date from tablename
where id=4
但它给出的结果是
dates salary
2015-09-28 1000
2015-09-29 1000
2015-09-30 1000
您需要 sub-select 从 tablename
创建一系列日期,然后 LEFT JOIN
添加工资数据:
SELECT d.dates, t.salary
FROM (
SELECT generate_series(startdate, enddate, interval '1 day') dates
FROM tablename) d
LEFT JOIN tablename t ON t.startdate = d.dates;
假设您的 table 中有更多薪水数据,您必须更改连接子句以包含更多限定词,例如 employee_id
左右。
这是一个可能的方法:
with cte as (
select
generate_series(startdate, enddate, '1 day'::interval)::date as date,
salary, startdate
from tablename
where id=4
)
select
date,
case when date = startdate then salary end as salary
from cte
但是,我告诉你这可能不是防弹的。例如,如果您的数据如下所示:
Salary Startdate Enddate
1000 2015-09-28 2015-09-30
1000 2015-10-01 2015-10-05
2015 年 10 月 1 日,您仍将有第二个 1000 条目。
一种更可靠但效率低得多的方法是使用 lag
分析函数,它会评估以上所有内容,但也会考虑以前的薪水:
with cte as (
select
generate_series(startdate, enddate, '1 day'::interval)::date as date,
salary, startdate,
lag(salary) over (partition by id order by startdate) as prior_sal
from tablename
where id=4
)
select
date,
case
when (prior_sal is null or prior_sal != salary) and
date = startdate then salary
end as salary
from cte
根据这种情况发生的可能性可能有助于确定哪种方法更好。
嗨,我想要日期和相应的值在 postgres 中是唯一的 我有一个 table,其中给出了开始日期、结束日期和薪水。我想计算日期系列和该期间的工资。 table 就像
Salary Startdate Enddate
1000 "2015-09-28" "2015-09-30"
我希望查询结果像
dates salary
2015-09-28 1000
2015-09-29
2015-09-30
我使用的查询是
select salary, generate_series("startdate", "enddate", '1 day'::interval)::date as date from tablename
where id=4
但它给出的结果是
dates salary
2015-09-28 1000
2015-09-29 1000
2015-09-30 1000
您需要 sub-select 从 tablename
创建一系列日期,然后 LEFT JOIN
添加工资数据:
SELECT d.dates, t.salary
FROM (
SELECT generate_series(startdate, enddate, interval '1 day') dates
FROM tablename) d
LEFT JOIN tablename t ON t.startdate = d.dates;
假设您的 table 中有更多薪水数据,您必须更改连接子句以包含更多限定词,例如 employee_id
左右。
这是一个可能的方法:
with cte as (
select
generate_series(startdate, enddate, '1 day'::interval)::date as date,
salary, startdate
from tablename
where id=4
)
select
date,
case when date = startdate then salary end as salary
from cte
但是,我告诉你这可能不是防弹的。例如,如果您的数据如下所示:
Salary Startdate Enddate
1000 2015-09-28 2015-09-30
1000 2015-10-01 2015-10-05
2015 年 10 月 1 日,您仍将有第二个 1000 条目。
一种更可靠但效率低得多的方法是使用 lag
分析函数,它会评估以上所有内容,但也会考虑以前的薪水:
with cte as (
select
generate_series(startdate, enddate, '1 day'::interval)::date as date,
salary, startdate,
lag(salary) over (partition by id order by startdate) as prior_sal
from tablename
where id=4
)
select
date,
case
when (prior_sal is null or prior_sal != salary) and
date = startdate then salary
end as salary
from cte
根据这种情况发生的可能性可能有助于确定哪种方法更好。