2017-02-16 98 views
-1

我有一個這樣的表。在SQL Server 2012中選擇連續ID

ID    Installment ID  DateDue 
------------------------------------------------------------  
000000000008 29     2017-03-15 00:00:00.000 
000000000008 30     2017-04-15 00:00:00.000 
000000000008 32     2017-06-15 00:00:00.000 
000000000008 33     2017-07-15 00:00:00.000 
000000000008 34     2017-08-15 00:00:00.000 

我需要的是什麼(所以在這個例子32,33,34)返回上只有3個連續成功分期付款的數據,在特定日期範圍之間的選擇查詢。

假設失敗在另一個表(31)中填充。

所以我想要一個序列號,分期付款ID的返回。

+0

6,6,7 - 連續的? – DarkKnight

+0

對不起,糾正。 6,7,8 –

+0

如果您有3,4,6,7,8,9,它應該返回什麼? – DarkKnight

回答

0

您可以使用SqlServer 2012中的LEADLAG函數,並且可以這樣做。

Demo here

;WITH cte1 AS 
(
SELECT * , datepart(m,(lead(datedue) OVER(ORDER BY installmentid)))-DATEPART(m,datedue) nowtonext 
     ,DATEPART(m,datedue)-datepart(m,(lag(datedue) OVER(ORDER BY installmentid))) prevtonow 
     ,ROW_NUMBER() OVER(ORDER BY installmentid) as rn 
FROM YourTable 
), 
cte2 AS 
(
SELECT rn,id,installmentid,datedue,nowtonext,prevtonow 
     ,lead(prevtonow) OVER(ORDER BY rn) AS prev 
     ,lag(nowtonext) OVER(ORDER BY rn) AS nxt 
FROM cte1 
) 

SELECT id,installmentid,datedue 
FROM cte1 
WHERE rn BETWEEN (SELECT rn-1 FROM cte2 WHERE nowtonext = 1 AND prevtonow=1 AND prev=1 AND nxt=1) 
      and (SELECT rn+1 FROM cte2 WHERE nowtonext = 1 AND prevtonow=1 AND prev=1 AND nxt=1) 
0

您可以使用下面的查詢,以返回其連續InstallmentID數的連續記錄的島嶼:

;WITH CTE_Group AS (
    SELECT ID, 
      InstallmentID, 
      DateDue, 
      ROW_NUMBER() OVER (PARTITION BY ID 
          ORDER BY DateDue) - InstallmentID AS grp 
    FROM mytable 
    WHERE DateDue BETWEEN @startDate AND @endDate 
), CTE_Count AS (
    SELECT ID, InstallmentID, DateDue, 
      COUNT(*) OVER (PARTITION BY ID, grp) AS cnt 
    FROM CTE_Group 
) 
SELECT ID, InstallmentID, DateDue 
FROM CTE_Count 
WHERE cnt >= 3 

如果你想只有3記錄了每個島的,然後您可以使用ROW_NUMBERPARTITION BY cnt條款來提取該島的前3條記錄。

說明:第一CTE,CTE_Group的查詢,以便識別具有預定時間範圍(​​)內的連續InstallmentID號碼連續記錄使用「行號特技之間差」。從CTE_Group

輸出:

ID InstallmentID DateDue  grp 
------------------------------------ 
8 29    2017-03-15 -28 
8 30    2017-04-15 -28 
8 32    2017-06-15 -29 
8 33    2017-07-15 -29 
8 34    2017-08-15 -29 

第二CTE,CTE_Count的查詢,以便計算每個島的人口使用COUNT() OVER()。從CTE_Count

輸出:

ID InstallmentID DateDue  Cnt 
----------------------------------- 
8 32    2017-06-15 3 
8 33    2017-07-15 3 
8 34    2017-08-15 3 
8 29    2017-03-15 2 
8 30    2017-04-15 2 

使用CTE_Count,我們可以很容易地篩選出屬於具有2以下的人口的島嶼記錄。

Demo here