2016-06-17 23 views
2
declare @tab table 
      (
       BatchID INT, 
       Code VARCHAR(20), 
       CommType INT, 
       LastStatus VARCHAR(5), 
       SourceModiifedLastDate varchar(30) 
      ) 

INSERT INTO @tab(BatchID, Code, CommType, LastStatus, SourceModiifedLastDate) 
VALUES (1, 'A003-3', 3, 'I', '2013-06-17 21:28:01.827'), 
     (2, 'A004-1', 1, 'I', '2014-06-17 21:28:01.827'), 
     (6, 'A003-3', 3, 'U', '2015-06-17 21:28:01.827'), 
     (9, 'A003-3', 3, 'D', '2015-06-17 21:28:01.827'), 
     (11, 'A004-1', 3, 'D', '2013-06-17 21:28:01.827'), 
     (12, 'A004-1', 1, 'I', '2015-06-17 21:28:01.827'), 
     (16, 'A005-3', 3, 'I', '2011-06-17 21:28:01.827'), 
     (19, 'A005-3', 3, 'D', '2013-0617 21:28:01.827'), 
     (20, 'A006-3', 3, 'U', '2011-06-17 21:28:01.827'), 
     (21, 'A006-3', 3, 'I', '2013-0617 21:28:01.827') 

Select * from @tab 

在我的示例數據中,我只需要獲取Laststatus ='D'記錄根據最新BatchID。如何獲得基於批號的最新記錄

例如,如果你看到的代碼=「A003-3」它得到了插入,更新和刪除,我需要得到這個紀錄

如果你看到的代碼=「A004-1」它得到了插入,刪除和插入我不需要這個記錄。

輸出應該是:

BatchID Code CommType LastStatus SourceModiifedLastDate 
--------------------------------------------------------------- 
9  A003-3  3   D  2015-06-17 21:28:01.827 
19  A005-3  3   D  2013-06-17 21:28:01.827 

我需要根據最新BatchID和最新的日期只得到最新刪除的記錄。

我試過使用MAX條件和GROUP BY來過濾記錄,但我無法得到我在找什麼。

請大家幫我想想辦法

回答

3
select tt.* 
from (select t.* 
      , row_number() over (partition by Code order by BatchId desc) as rn 
     from @tab t 
    ) tt 
where tt.rn = 1 
    and tt.LastStatus = 'D'; 
+0

有道理謝謝 – mohan111

0

做那朵的典型方式是使用row_number()

select t.* 
from (select t.*, 
      row_number() over (partition by Code order by BatchId desc) as seqnum 
     from @tab t 
    ) t 
where seqnum = 1; 

做的老式的方法(前窗功能)可能是這樣的:

select t.* 
from @tab t 
where t.BatchId = (select max(t2.BatchId) 
        from @tab t2 
        where t2.Code = t.Code 
       ); 
+0

它甚至還沒有接近給出任何結果......完全錯誤的結果集 – mohan111

+0

看到我的回答那些BatchIds選項並且您的問題陳述不明確 – Paparazzi

+0

@ gordon-linoff在使用BatchId而不是代碼時犯了一個錯誤。這是這個答案的問題。 – Sam

0
SELECT tab1.BatchId, tab1.Code, tab1.CommType, tab1.LastStatus, tab1.SourceModiifedLastDate 
FROM @tab tab1 
INNER JOIN (
SELECT Code, MAX(SourceModiifedLastDate) MaxSourceModiifedLastDate 
FROM @tab 
GROUP BY Code) tab2 
ON tab2.Code = tab1.Code 
AND tab2.MaxSourceModiifedLastDate = tab1.SourceModiifedLastDate 
WHERE tab1.LastStatus = 'D' 
1

下面是一個使用CTE和濾波只爲那些最後的動作爲刪除

; 
WITH CTE1 AS ( 
    SELECT *, RANK() OVER (partition by Code ORDER BY BatchID DESC) [CodeRank] 
    FROM @tab) 
SELECT * 
FROM CTE1 
WHERE CodeRank = 1 and LastStatus = 'D'