查询以获取早于开始日期的日期行(不是简单的WHERE)

时间:2016-08-09 10:53:46

标签: sql-server sql-server-2012

我觉得这很简单,但我不能把手指放在查询上。我正在尝试查找员工的所有活动,这些活动与他们在特定地点的开始日期相对应。

create table Locations (EmployeeID int, LocationID int, StartDate date);

create table Activities (EmployeeID int, ActivityID int, [Date] date);

insert into Locations values 
    (1, 10, '01-01-2010')
    , (1, 11, '01-01-2012')
    , (1, 11, '01-01-2013');

insert into Activities values 
    (1, 1, '02-01-2010')
    , (1, 2, '04-01-2010')
    , (1, 3, '06-06-2014');

预期结果:

EmployeeID  LocationID  StartDate       EmployeeID  ActivityID  Date
1           10          '01-01-2010'    1           1           '02-01-2010'
1           10          '01-01-2010'    1           2           '04-01-2010'
1           11          '01-01-2013'    1           3           '06-06-2014'

到目前为止,我有这个,但它并没有完全给我我希望的结果。我不得不仅引用最近位置的信息,la.StartDate <= a.Date没有过滤掉这些信息,也包括来自旧位置的信息。

select *
from Locations la
    inner join Activities a on la.EmployeeID = a.EmployeeID
        and la.StartDate <= a.Date

2 个答案:

答案 0 :(得分:0)

试试这个:

with Locations as (
select
*
from (values 
    (1, 10, '01-01-2010')
    , (1, 11, '01-01-2012')
    , (1, 11, '01-01-2013')
) la (EmployeeID, LocationID, StartDate)
),
Activities as (
select
*
from (
values
    (1, 1, '02-01-2010')
    , (1, 2, '04-01-2010')
    , (1, 3, '06-06-2014')
) a (EmployeeID, ActivityID, [Date])
)
select 
    la.*,
    a.*
from Activities a
cross apply (
    select
    *
    from (
        select 
            la.*,
            ROW_NUMBER() OVER (
                PARTITION BY
                    EMPLOYEEID
                ORDER BY
                    DATE DESC
            ) seqnum
        from Locations la 
        where 
            la.EmployeeID = a.EmployeeID and 
            la.StartDate <= a.Date
    ) la
    where
        la.seqnum = 1
) la

答案 1 :(得分:0)

谢谢大家,但我找到了答案:

select *
from LocationAssociations la
    inner join Activities a on la.EmployeeID = a.EmployeeID
        and la.StartDate = (select max(StartDate) from LocationAssociations where StartDate >= la.StartDate and StartDate <= a.Date)