SQL配对相应的重复行和计算天数(SSMS)

时间:2013-12-04 23:18:50

标签: sql sql-server-2008 tsql

我有一张表格,其中包含为抵押担保品处理的不同类型的交易。我提供的报告解决方案可帮助用户确定两次单独交易之间的天数。我面临的挑战是一组交易可能多次发生,我不知道如何将一个交易与另一个相应的交易配对,并计算这两个交易之间的天数。例如,我有一个包含1个抵押品的交易的表,这些抵押品已多次返回和恢复。每次发生返回时,都会在此表中发布一个事务,并且该事务与恢复相同:

transaction type    collateral  transaction date
reinstatement       123         11/24/2013
returned            123         11/21/2013
reinstatement       123         1/2/2013
returned            123         1/1/2013

规则1:退回的交易必须之后是恢复

规则2:两个相应交易之间没有关系链接

结果:

collateral  days between transactions
123         1
123         3

目前,我必须运行所有退回和恢复交易的摘录,然后必须手动配对每个交易,然后计算两者之间的天数。任何人都可以在SQL中包含这种逻辑吗?我目前正在使用SQL Server 2008.谢谢!

1 个答案:

答案 0 :(得分:0)

IT不是最漂亮的查询,我没有大量的测试数据,但这将通过您提供的数据满足您的需求:

--Test Data
CREATE TABLE MORTGAGE (transactionType VARCHAR(20),collateral INT, transactionDate DATETIME)

INSERT INTO MORTGAGE VALUES('reinstatement',123,'Nov 24 2013')
INSERT INTO mortgage VALUES('returned',123,'Nov 21 2013')
INSERT INTO mortgage VALUES('reinstatement',123,'Jan 2 2013')
INSERT INTO mortgage VALUES('returned',123,'Jan 1 2013')

--Query
SELECT res1.collateral
     , DATEDIFF(DAY,res1.transactiondate,res2.transactiondate) AS [days between transactions]
FROM
    (SELECT TOP 100 PERCENT 
        TRANSACTIONTYPE, 
        COLLATERAL, 
        TRANSACTIONDATE
        ,ROW_NUMBER () over (partition by transactiontype order by transactiondate) artificialid
     FROM MORTGAGE 
     WHERE TRANSACTIONTYPE='returned'
     ORDER BY transactionDate) res1
INNER JOIN
    (SELECT TOP 100 PERCENT
        TRANSACTIONTYPE, 
        COLLATERAL, 
        TRANSACTIONDATE
        ,ROW_NUMBER () over (partition by transactiontype order by transactiondate) artificialid
     FROM MORTGAGE mret
     WHERE TRANSACTIONTYPE='reinstatement'
     ORDER BY transactionDate) res2
ON res1.artificialid = res2.artificialid
AND res1.TRANSACTIONDATE <> res2.TRANSACTIONDATE 
AND res1.TRANSACTIONDATE <> res2.TRANSACTIONDATE 

--Results
collateral  days between transactions
123         1
123         3