我想比较表中的行并找出不匹配

时间:2016-07-07 08:06:38

标签: sql sql-server sql-server-2008

enter image description here

我希望查询能够将所有列的最后三行和另一列指定不匹配的类型,即会计,货币等等。

任何人都能帮助我吗?

1 个答案:

答案 0 :(得分:0)

不确定你想要什么,但看看这个

/*
drop table t
create table  T (ticker VARCHAR(1), accounting varchar(1), currency varchar(1), multiplier varchar(1), dte date)
truncate table t
INSERT INTO T VALUES
('a','p','u','m','2016-06-06'),
('a','p','u','m','2016-06-07'),
('b','g','c','m','2016-06-07'),
('c','p','u','b','2016-06-07')

*/

select u.ticker,u.accounting,u.currency,u.multiplier,
        concat(diff,',',diff2,',',diff3) as diffs        
from
(
select t.*,
        case when t.accounting <> t.a2 or t.accounting <> t.a3 then 'Accounting' else '' end as diff,
        case when t.currency <> t.c2 or t.currency <> t.c3 then 'Currency' else '' end as diff2,
        case when t.multiplier <> t.m2 or  t.multiplier <> t.m3  then 'Multiplier'  else '' end as diff3

from
(

select s.*,
        case when s.rn =  1 then lead(s.accounting, 1,0) OVER (ORDER BY s.rn) 
            when s.rn =  2 then lag(s.accounting, 1,0) OVER (ORDER BY s.rn)
            when s.rn =  3 then lag(s.accounting, 1,0) OVER (ORDER BY s.rn)  
        end as a2,

        case when s.rn =  1 then lead(s.accounting, 2,0) OVER (ORDER BY s.rn) 
             when s.rn =  2 then lead(s.accounting, 1,0) OVER (ORDER BY s.rn) 
             when s.rn =  3 then lag(s.accounting, 2,0) OVER (ORDER BY s.rn) 
        end as a3,

        case when s.rn =  1 then lead(s.currency, 1,0) OVER (ORDER BY s.rn) 
            when s.rn =  2 then lag(s.currency, 1,0) OVER (ORDER BY s.rn)
            when s.rn =  3 then lag(s.currency, 1,0) OVER (ORDER BY s.rn)  
        end as c2,

        case when s.rn =  1 then lead(s.currency, 2,0) OVER (ORDER BY s.rn) 
             when s.rn =  2 then lead(s.currency, 1,0) OVER (ORDER BY s.rn) 
             when s.rn =  3 then lag(s.currency, 2,0) OVER (ORDER BY s.rn) 
        end as c3,

        case when s.rn =  1 then lead(s.multiplier, 1,0) OVER (ORDER BY s.rn) 
            when s.rn =  2 then lag(s.multiplier, 1,0) OVER (ORDER BY s.rn)
            when s.rn =  3 then lag(s.multiplier, 1,0) OVER (ORDER BY s.rn)  
        end as m2,

        case when s.rn =  1 then lead(s.multiplier, 2,0) OVER (ORDER BY s.rn) 
             when s.rn =  2 then lead(s.multiplier, 1,0) OVER (ORDER BY s.rn) 
             when s.rn =  3 then lag(s.multiplier, 2,0) OVER (ORDER BY s.rn) 
        end as m3

from
(
select  top 3
        row_number() over (order by dte) rn,
        t.ticker,t.accounting,t.currency,t.multiplier
from    t
where   dte = (select max(dte) from t)
) s
--order by s.rn 
) t
) u