2014-04-24 62 views
3

我進入行到一個DB每一條記錄被更新刪除順序dupelicates

任務可能會去開始時間的事件管理系統 - >編輯 - >批准 - >拒絕 - >編輯 - 覈准 - >完成

但是它可能會幾次被人所以有在像這樣

開始一個狀態的多個條目更新 - >編輯 - >編輯 - >編輯 - >批准 - >拒絕 - >拒絕 - >編輯 - 審批 - >完成

我想刪除ential重複但如果該狀態通過使用

SELECT taskid,version,TaskStatus, ROW_NUMBER() OVER (Partition by taskid,taskstatus ORDER BY taskid, cast(version as int)) As SetId 
into sqrank from sqtaskflow 

它生產

後來發生在

我試圖分區

ID VER  STATUS   RANK 
16 1 QA Complete   1 
16 2 QA Complete   2 
16 3 QA Complete   3 
16 4 In Queue   1 
16 5 In Queue   2 
16 6 In Queue   3 
16 7 QA Complete   4 
16 8 QA Complete   5 
16 9 QA Complete   6 
16 10 Task complete   1 

希望的輸出將是

ID VER  STATUS   RANK 
16 1 QA Complete   1 
16 4 In Queue   1 
16 7 QA Complete   4 
16 10 Task complete   1 

回答

4

假設version是總是連續的,沒有差距...

SELECT 
    taskid, 
    MIN(version) AS first_version, 
    TaskStatus, 
    COUNT(*)  AS repeats 
FROM 
(
    SELECT 
    taskid, 
    CAST(version AS INT) AS version, 
    TaskStatus, 
    ROW_NUMBER() OVER (Partition by taskid    ORDER BY taskid, cast(version as int)) AS task_ordinal, 
    ROW_NUMBER() OVER (Partition by taskid, taskstatus ORDER BY taskid, cast(version as int)) AS task_status_ordinal 
    FROM 
    sqtaskflow 
) 
    AS sequenced 
GROUP BY 
    taskid, 
    TaskStatus, 
    task_ordinal - task_status_ordinal 
ORDER BY 
    taskid, 
    TaskStatus, 
    MIN(version) 


實施例數據

ID VER STATUS   RANK Ver-Rank Group 

16 1  QA Complete  1  0   16,QA Complete,0 
16 2  QA Complete  2  0   16,QA Complete,0 
16 3  QA Complete  3  0   16,QA Complete,0 

16 4  In Queue  1  3   16,In Queue,3 
16 5  In Queue  2  3   16,In Queue,3 
16 6  In Queue  3  3   16,In Queue,3 

16 7  QA Complete  4  3   16,QA Complete,3 
16 8  QA Complete  5  3   16,QA Complete,3 
16 9  QA Complete  6  3   16,QA Complete,3 

16 10 Task complete 1  9   16,Task Complete,9 

編輯:

查詢修改以創建一個順序值(無缺口)代替version使用。

+0

這是關閉 - 不幸的版本可能有差距 - 對不起,我沒有提到上述 – Rob

+0

完美謝謝! - 認爲在ROW_NUMBER()OVER上有錯誤(由taskid分區,(額外逗號) – Rob

+0

@Rob - 是的,很好的地方:) – MatBailie