根据日期范围

时间:2015-09-16 20:51:27

标签: sql sql-server-2008

我有3张表如下:

policyTable

policy_id employee_id policy_start_date premium 1000001 2000001 2010-03-24 560.1 1000002 2000003 2013-11-01 865.6 1000023 2000201 2012-03-07 435.2 ... ... ...

employeeTable

employee_id department_id job_title_key start_date end_date 2000001 5 1248 2009-05-01 2009-09-23 2000001 5 1248 2009-09-23 2010-02-01 2000001 3 1302 2010-02-01 2011-06-15 2000003 4 2054 2008-03-01 2009-05-12 2000003 4 2054 2009-05-12 2012-01-13 2000003 4 2054 2012-01-13 2014-02-09 2000003 7 5023 2014-02-09 NULL 2000201 2 3125 2010-03-06 2012-01-05 2000201 2 3125 2012-01-05 2013-08-07 2000201 5 1265 2013-08-07 2015-02-20 ...

departmentTable

department_id department_name 2 finance 3 accounting 4 software 5 sales 7 marketing ... ...

我的目标是加入这些表,以使用列policy_id, employee_id, policy_start_date, premium, job_title_key, department_name为每个策略获取一条记录。我现在的问题是employeeTable,它为每个员工提供了多个不同职位的记录。我只需要为每个政策获得每个员工的一条记录。标准是选择policy_start_date介于员工start_dateend_date之间的那个。

所以我最后想要的表是:

policy_id employee_id policy_start_date premium job_title_key department_name 1000001 2000001 2010-03-24 560.1 1302 accounting 1000002 2000003 2013-11-01 865.6 2054 software 1000023 2000201 2012-03-07 435.2 3125 finance ... ... ... ... ... ...

我尝试将SELECT AGGREGATE GROUP BY与联接一起使用,但是每个未汇总的列都需要进入GROUP BY,这对我来说不起作用。

2 个答案:

答案 0 :(得分:1)

<强> Sql Fiddle Demo

SELECT p.policy_id, e.employee_id, p.policy_start_date, e.job_title_key, d.department_name
FROM policyTable p
INNER JOIN employeeTable e 
   on p.employee_id = e.employee_id
   and p.policy_start_date between e.start_date 
                               and CASE 
                                     WHEN e.end_date IS NULL THEN GETDATE()
                                     ELSE e.end_date
                                   END
INNER JOIN departmentTable d
   on e.department_id = d.department_id

答案 1 :(得分:0)

    with order
    (With Employee_correction as (select 
    employee_id ,   department_id  ,  job_title_key  ,  start_date    , 
    (case when   end_date is null then GETDATE ( ) else end_date end) as end_date
    from employeeTable)
    select policy_id, employee_id ,
    max(policy_start_date) as policy_start_date 
     from policyTable a
    join Employee_correction b on a.employee_is=b.employee_id
    and policy_start_date between start_date and end_date group by policy_id, employee_id )
    select c.policy_id ,c.employee_id ,c.policy_start_date,c.job_title_key,premium,department_name from employeeTable c
    join order on   order.policy_id=c.policy_id
 and order.employee_id=c.employee_id 
 and order.policy_start_date=c.policy_start_date
    join policyTable d on
 order.policy_id=d.policy_id and  
  order.employee_id=d.employee_id 
  and order.policy_start_date=d.policy_start_date
   join departmentTable e on c.department_id=e.department_id

我已经对Employee进行了更正,假设当最大日期为空时所以日期是今天。 另外,为避免重复,我在日期进行了最大聚合。