2015-10-26 45 views
0

我有一張表,需要獲取兩個日期之間的差異,以獲得非常相似的一組記錄。今天我嘗試了一些方法,但似乎無法讓這個工作。SQL中的相似記錄之間的日期差異

示例表:

Payment_ID | Created_Date | Version_ID |  Status 
---------------------------------------------------------- 
    1526 | 20/10/2015 |  1  | Opened 
    1526 | 20/10/2015 |  2  | Verified Open 
    1526 | 22/10/2015 |  3  | Assigned 
    1526 | 23/10/2015 |  4  | Contact Made 
    1859 | 20/10/2015 |  1  | Opened 
    1859 | 20/10/2015 |  2  | Verified Open 
    1859 | 22/10/2015 |  3  | Assigned 
    1859 | 22/10/2015 |  3.5 | Re-Assigned 
    1859 | 22/10/2015 |  4.5 | Contact Failed 
    1859 | 23/10/2015 |  4  | Contact Made 
    1859 | 24/10/2015 |  5  | Assigned Updated 
    1859 | 25/10/2015 |  6  | Contact Made 
    1859 | 26/10/2015 |  7  | Resolved 
    1859 | 21/10/2015 |  8  | Closed 
    1852 | 26/10/2015 |  1  | Opened 
    1778 | 21/09/2015 |  1  | Opened 
    1778 | 22/09/2015 |  2  | Verified Open 
    1778 | 23/09/2015 |  3  | Assigned 
    1778 | 24/09/2015 |  4  | Contact Made 
    1778 | 25/09/2015 |  5  | Assigned Updated 

要求是返回針對給定StatusPayment_IDStatusDateDiff,在這種情況下,Contact_Made一個且僅第一個如果Payment_ID具有多於一個,則請將該日期與之前的狀態日期之間的差異作爲它們中的任何一個。

因此,採取1526「Contact_Made」是在24/10/2015和以前的狀態,不管是什麼,是23/10/2015所以差異是1

對於上面是這樣的:

Payment_ID | StatusDateDiff 
----------------------------- 
    1526  |  1 
    1859  |  1 
    1852  |  0 
    1778  |  1 

我試過幾個子查詢,以獲得distinct Payment_IDMin(Created_Date),但造成了重複一次放在一起。

也嘗試了一個公共表表達式,但導致相同 - 雖然我不太熟悉它們。

任何想法,將不勝感激。

+1

這是什麼部分使用SQL-Server,以及使用Oracle的部分是什麼? –

回答

0

這是未經測試的,但這應該指向正確的方向。您可以使用窗口化的ROW_NUMBER()函數來確定哪些值是最新的,然後執行DATEDIFF()來查找它們不同的天數。

編輯:我只注意到你有一個SQL Server標籤和Oracle標籤 - 這個答案是SQL Server

;With Ver As 
(
    Select *, 
      Row_Number() Over (Partition By Payment_Id Order By Version Desc) Row_Number 
    From Table 
) 
Select  Latest.Payment_Id, 
      DateDiff(Day, Coalesce(Previous.Created_Date, Latest.CreatedDate), Latest.CreatedDate) As StatusDateDiff 
From  Ver  As Latest 
Left Join Ver  As Previous On Latest.Payment_Id = Previous.Payment_Id 
            And Previous.Row_Number = 2 
Where  Latest.Row_Number = 1 
1

使用LAG()(在SQL Server中可用2012+):

select payment_id, datediff(day, prev_created_date, created_date) 
from (select t.*, 
      lag(created_date) over (partition by payment_id order by created_date) as prev_created_date, 
      row_number() over (partition by payment_id, status order by created_date) as seqnum 
     from t 
    ) t 
where status = 'Contact Made' and seqnum = 1;