如何根据批次ID获取最新记录

时间:2016-06-17 16:15:52

标签: sql sql-server tsql sql-server-2012 sql-server-2008-r2

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。

例如,如果您看到Code =' 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来过滤记录,但我无法获得我正在寻找的内容。

请帮我找一个解决方案

4 个答案:

答案 0 :(得分: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';

答案 1 :(得分:1)

这是一个使用CTE并仅过滤那些将最后一个操作作为删除的BatchId的选项

;
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'

答案 2 :(得分:0)

执行tis的典型方法是使用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
                  );

答案 3 :(得分: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'