【发布时间】:2013-11-13 16:47:46
【问题描述】:
问题:我已经在表格中存储了工资信息的日期。我需要每年显示一个结果。对于每一年,我想显示前一年的最大日期记录。问题是有些年份没有数据(工资没有变化)。我需要这些行包含该年之前的最大记录(可能是 2 年前甚至 3 年前)。
如果每一行都有数据,我现在的查询就可以工作……但它不考虑没有数据的年份。如何更新此 sql 以获取以下所需结果:
数据示例:
sch_sal_svc.beg_date -------sch_sal_svc.beg_date.per_plan_data
- 1/1/2007---100
- 6/1/2007---200
- 1/1/2008---300
- 1/1/2011---400
- 8/1/2011---500
- 9/1/2012---600
当前结果
- 1/1/2008---200
- 1/1/2011---300
- 1/1/2012---500
期望的结果
- 1/1/2008---200
- 1/1/2009---300
- 1/1/2010---300
- 1/1/2011---300
- 1/1/2012---500
SQL:
SELECT
years.control_id,
years.ssn,
ebe.plan_id,
to_number(to_char(years.sal_date,'yyyy')),
null as per_plan_salary,
null as per_vest_hours,
null as per_credsvc_hours,
LEAST(s.rate_1,cl.comp_genl),
null as salary_1,
null as per_comm,
null as per_overtime,
null as per_ncr,
null as salary_2
FROM
sch_sal_svc s
, (select distinct ssn, control_id, TRUNC(beg_date,'YEAR') as sal_date from sch_sal_svc where beg_date > to_date('12/31/1900', 'mm/dd/yyyy')) years
, employee_benefit_elig ebe, compliance_limits cl
WHERE
years.ssn = ebe.ssn
and years.control_id = ebe.control_id
and to_number(to_char(years.sal_date,'yyyy')) = cl.limit_year
and to_number(to_char(years.sal_date,'yyyy')) <= to_number(to_char(sysdate,'yyyy'))
and s.beg_date = (
select max(s2.beg_date) from sch_sal_svc s2
where s2.ssn = years.ssn and s2.control_id = years.control_id
and s2.beg_date <= years.sal_date
)
and s.ssn = years.ssn
and s.control_id = years.control_id
and ebe.benefit_id = 'DB'
and ebe.control_id = 'CLIENT'
and ebe.plan_id in ('100', '200')
【问题讨论】:
-
这是在 Stackoverflow 上编写 SQL 问题的好技巧,使用 sqlfiddle.com 创建“示例数据库”并在问题中发布链接,这将让您和发布答案的人“检查他们的工作”以查看查询的输出是您要查找的内容。为了获得漂亮的表格,例如结果集使用this website(由SO用户Sensful创建)并将表格包装在
<pre></pre>html标签中