自我加入排名查询

时间:2015-03-18 12:31:42

标签: sql sql-server tsql sql-server-2012 self-join

我想在以下查询中执行自联接:

select 
RANK() OVER (PARTITION BY CARD_ID, BE_BUSINESS_DATE ORDER BY CARD_TXN_SEQ_NUMBER) as Trip_Leg_Id
from  [dbo].[Src_Nol_Txns] s1
inner join 

这样,我加入当前记录的排名为-1的记录 怎么实现呢?

3 个答案:

答案 0 :(得分:4)

这是一种方法

With TripID AS
(
select 
RANK() OVER (PARTITION BY CARD_ID, BE_BUSINESS_DATE ORDER BY CARD_TXN_SEQ_NUMBER) as Trip_Leg_Id
from  [dbo].[Src_Nol_Txns] s1
)
select *
from TripID a
join TripID b
   on b.Trip_Leg_Id=a.Trip_Leg_Id - 1
  and a.CARD_ID=b.CARD_ID
  and a.BE_BUSINESS_DATE =b.BE_BUSINESS_DATE 

答案 1 :(得分:1)

with cte as 
(  SELECT * ,
          LAG(CARD_TXN_SEQ_NUMBER, 1,0) OVER (PARTITION BY CARD_ID, BE_BUSINESS_DATE ORDER BY CARD_TXN_SEQ_NUMBER) AS PreviousSEQ   
     FROM table ); 
select cte1.*, cte2.* 
  from cte as cte1 
  join cte as cte2 
    on cte2.CARD_ID = cte1.CARD_ID 
   and cte2.BE_BUSINESS_DATE = cte1.BE_BUSINESS_DATE 
   and cte2.CARD_TXN_SEQ_NUMBER = cte1.PreviousSEQ
   and cte1.PreviousSEQ <> cte1.CARD_TXN_SEQ_NUMBER;  

我认为最后并将处理重复

答案 2 :(得分:1)

因为我可以访问sql小提琴,所以我可以举例说明它如何在没有任何selfjoin的情况下使用LAG:

link:http://www.sqlfiddle.com/#!6/1296a/4/0

select *
     , SEQN_LAST = LAG(CARD_TXN_SEQ_NUMBER, 1, NULL) 
       OVER 
       ( PARTITION BY CARD_ID, BE_BUSINESS_DATE 
         ORDER BY CARD_TXN_SEQ_NUMBER) 
     , DUMMY_LAST = LAG(DUMMY, 1, NULL) 
       OVER 
       ( PARTITION BY CARD_ID, BE_BUSINESS_DATE 
         ORDER BY CARD_TXN_SEQ_NUMBER) 
     , SEQN_NEXT = LAG(CARD_TXN_SEQ_NUMBER, 1, NULL) 
       OVER 
       ( PARTITION BY CARD_ID, BE_BUSINESS_DATE 
         ORDER BY CARD_TXN_SEQ_NUMBER DESC) 
     , DUMMY_NEXT = LAG(DUMMY, 1, NULL) 
       OVER 
       ( PARTITION BY CARD_ID, BE_BUSINESS_DATE 
         ORDER BY CARD_TXN_SEQ_NUMBER DESC) 
from ( values 
      ('1','2012-01-01',1,'dummy1'),
      ('1','2012-01-01',2,'dummy2'),
      ('1','2012-01-01',3,'dummy3'),
      ('2','2012-01-01',1,'dummy1'),
      ('2','2012-01-01',2,'dummy2'),
      ('2','2012-01-01',3,'dummy3')) 
      Src_Nol_Txns(CARD_ID, BE_BUSINESS_DATE, CARD_TXN_SEQ_NUMBER, DUMMY)
order by CARD_ID, BE_BUSINESS_DATE, CARD_TXN_SEQ_NUMBER