组合2个表从Table2 type2中提取所有值,并从Table1&中排除重复的列值。使用表3 type2中table2的值

时间:2018-02-24 17:02:01

标签: sql tsql ssis

我有2张桌子。我希望加入这些表并记录历史数据(type2)并相应地更新StartDate和EndDate。 id'E7C7'在Table1(type2)中有三个条目,在Table2(type1)中有一个条目。 表2具有最新数据。

Table1中数据的默认StartDate是1/1/2018,默认EndDate是9999-12-31。

自从1/1/2018以来,E7C7已经改变了3次标题。结果集应包括E7C7的所有过去和现在数据以及表2中的任何新条目。结果集将旧记录标记为[current] ='N',新记录[current] ='Y'。表1还包含已更改记录的最新数据。 Table2的默认StartDate是GetDate(),默认EndDate是9999-12-31

{{1}}

1 个答案:

答案 0 :(得分:0)

检查此查询。我根据你的预期结果写了它

declare @t1 table (id varchar(10), mod_date date, old_value varchar(10), new_value varchar(10))
insert into @t1
values ('E7C7', '20180110', 'FSA', 'Sr FS'),('E7C7', '20180125', 'Sr FS', 'FS')
    ,('E7C7', '20180201', 'FS', 'FSA'),('EA23', '20180115', 'SFA', 'FM')

declare @t2 table (id varchar(10), number int, last_name varchar(10), title varchar(10))
insert into @t2
values ('2DB3', '12344', 'A', 'SLS'), ('C655', '12227', 'L', 'SA')
    , ('D0F7', '12228', 'K', 'I-CSR'), ('E7C7', '11937', 'H', 'FSA')
    , ('EA23', '1267', 'S', 'FM'), ('FCF1', '139', ' A', 'CAR')

;with cte as (
    select
        *, prev_date = lag(mod_date) over (partition by id order by mod_date, order_)
        , cnt = count(*) over (partition by id)
        , rn = row_number() over (partition by id order by mod_date, order_)
    from (
        select 
            a.id, a.number, a.last_name, a.title, b.mod_date, b.old_value, b.new_value, order_ = 1
        from 
            @t2 a
            left join @t1 b on a.id = b.id
        union all
        select
            t.id, q.number, q.last_name, null, t.mod_date, t.old_value, null, 0
        from (
            select
                *, cnt = count(*)over (partition by id)
            from
                @t1
            ) t
            join @t2 q on t.id = q.id
        where
            cnt = 1
    ) t
)
select
    id, number, last_name
    , title = coalesce(new_value, title, old_value)
    , StartDate = isnull(prev_date, iif(cnt = 1, '20180224', '20180101'))
    , EndDate = iif(cnt > rn, mod_date, '99991231') 
    , [Current] = iif(cnt = rn, 'Y', 'N')
from
    cte
order by id, rn desc

输出

id      number  last_name   title    StartDate    EndDate       Current
-----------------------------------------------------------------------
2DB3    12344   A           SLS      2018-02-24   9999-12-31    Y
C655    12227   L           SA       2018-02-24   9999-12-31    Y
D0F7    12228   K           I-CSR    2018-02-24   9999-12-31    Y
E7C7    11937   H           FSA      2018-01-25   9999-12-31    Y
E7C7    11937   H           FS       2018-01-10   2018-01-25    N
E7C7    11937   H           Sr FS    2018-01-01   2018-01-10    N
EA23    1267    S           FM       2018-01-15   9999-12-31    Y
EA23    1267    S           SFA      2018-01-01   2018-01-15    N
FCF1    139  A  CAR 2018-02-24  9999-12-31  Y