选择一组记录,这些记录是他们自己类型的最后一个记录

时间:2013-03-02 06:52:57

标签: sql tsql sql-server-2008-r2 group-by greatest-n-per-group

我有下表

LogCheque(LogChequeID,ChequeID,Date,HolderID)

每一行显示哪个Check(ChequeID)被转移到哪个日期的Whom(HolderID) 我想选择LogCheques列表,但每次检查只出现一次,显示最后一次转移

示例数据

LogChequeID     ChequeID    Date            HolderID  
1               1012        2013-01-10      200  
2               1526        2013-01-12      125  
3               1012        2013-01-19      413  
4               1526        2013-02-11      912  
5               1526        2013-02-17      800  

我想要的输出是

LogChequeID     ChequeID    Date            HolderID  
3               1012        2013-01-19      413
5               1526        2013-02-17      800

我试过了

select lch.ChequeID, lch.DateFa, lch.ChequeID
from LCheque lch
group by lch.ChequeID, lch.DateFa, lch.LChequeID
having lch.LChequeID = (select MAX(LChequeID) where ChequeID = lch.ChequeID)

但它会返回每一行。

任何帮助都会非常有帮助并且张开双臂赞赏:)提前感谢。

3 个答案:

答案 0 :(得分:4)

您可以使用CTE + ROW_NUMBER()排名功能

;WITH cte AS
 (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY ChequeID ORDER BY [Date] DESC) AS rn
  FROM dbo.LCheque 
  )
  SELECT *
  FROM cte
  WHERE rn = 1

SQLFiddle上的演示

EXISTS运算符

OR 选项

SELECT *
FROM dbo.LCheque t
WHERE EXISTS(
             SELECT 1
             FROM dbo.LCheque t2
             WHERE t.ChequeID = t2.ChequeID
             HAVING MAX(t2.[Date]) = t.[Date]
             )

SQLFiddle上的演示

APPLY()运算符

OR 选项

SELECT *
FROM dbo.LCheque t CROSS APPLY (
                                SELECT 1 
                                FROM dbo.LCheque t2
                                WHERE t.ChequeID = t2.ChequeID
                                HAVING MAX(t2.[Date]) = t.[Date]
                                ) o (IsMatch)

SQLFiddle上的演示

答案 1 :(得分:1)

  select lch.ChequeID,max(lch.Date),lch.HolderID  
  from LCheque lch
  group by lch.ChequeID,lch.HolderID  

答案 2 :(得分:1)

CTE更整洁(也许效率更高),但你差不多了。

select lch.ChequeID, lch.DateFa, lch.ChequeID
from LCheque lch
where lch.LChequeID = (select MAX(LChequeID) where ChequeID = lch.ChequeID)