2017-06-06 33 views
1

選擇不同我有一個任務表(每個任務可以有幾行),看起來是這樣的:的SQL Server:直到值被改變

TaskID | DateCreated | Status 
-------+-------------+------------ 
    1 | 01-01-2017 | Started 
    2 | 02-02-2017 | InProgress 
    1 | 02-02-2017 | Started 
    1 | 03-03-2017 | InProgress 
    2 | 03-03-2017 | InProgress 
    1 | 04-04-2017 | InProgress 
    2 | 04-04-2017 | Done 
    1 | 05-05-2017 | Done 

我有更多的列這是不相關的這個要求。

我在這裏需要的是選擇特定任務已經通過的實際狀態流。

例如,對於具有的TaskID = 1的任務,我希望得到以下結果:

TaskID | Status 
-------+------------- 
    1 | Started 
    1 | InProgress 
    1 | Done 

注:

  1. 該行可能會不排序

  2. 狀態可以重複,例如可以有一個任務,它的狀態流爲:

    Started ==> InProgress ==> Break ==> InProgress ==> Done 
    

    所以不會幫助我獲得了每項任務從每個狀態的獨特地位鍵入它通過

回答

1

在SQL 2012+你可以使用LAG

DECLARE @SampleData AS TABLE 
    (
    TaskID int, 
    DateCreated date, 
    Status varchar(20) 
) 

    INSERT INTO @SampleData 
    VALUES 
    (1, '2017-01-01', 'Started'), 
    (2, '2017-02-02', 'InProgress'), 
    (1, '2017-02-02', 'Started'), 
    (1, '2017-03-03', 'InProgress'), 
    (2, '2017-03-03', 'InProgress'), 
    (1, '2017-04-04', 'InProgress'), 
    (2, '2017-04-04', 'Done'), 
    (1, '2017-05-05', 'Done') 

    ;with temp as 
    (
    SELECT *, 
      lag(sd.Status,1,'') OVER(PARTITION BY sd.TaskID ORDER BY sd.DateCreated) AS PreviousRowStatus 
    FROM @SampleData sd 
) 
    SELECT t.TaskID, t.DateCreated, t.Status 
    FROM temp t 
    WHERE t.Status != t.PreviousRowStatus 
    ORDER BY t.TaskID 

返回

TaskID DateCreated Status 
-------------------------- 
1  2017-01-01 Started 
1  2017-03-03 InProgress 
1  2017-05-05 Done 
2  2017-02-02 InProgress 
2  2017-04-04 Done 

對於老版本,你可以使用Row_numberAPPLY

+0

太好了!我設法使用這個!非常感謝你!! – Batsheva

1

下面是查詢其中分區中會獲取你想要的結果。

select taskid,status(select taskid,status 
,row_number()over(partition by taskid,status order by taskid)rownum 
from [yourtablename])tmp 
where rownum = 1 
0

嘗試查詢(選擇不同):

SELECT DISTINCT TaskID, Status 
FROM   (SELECT TaskID, Status 
          FROM   task 
          ORDER BY TaskID) AS task_1 
WHERE  (TaskID = 1) 
ORDER BY Status DESC 

或者乾脆:

SELECT DISTINCT TaskID, Status 
FROM   task 
WHERE  (TaskID = 1) 
ORDER BY TaskID, Status DESC 

結果爲您的演示內容:

enter image description here