1

我有下表

LogCheque (LogChequeID, ChequeID, Date, HolderID)

每行显示在哪个日期将哪个支票 (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)

但它返回每一行。

张开双臂,任何帮助都会非常有帮助和感激:) 在此先感谢。

4

3 回答 3

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上的演示

于 2013-03-02T08:59:24.257 回答
1
  select lch.ChequeID,max(lch.Date),lch.HolderID  
  from LCheque lch
  group by lch.ChequeID,lch.HolderID  
于 2013-03-02T07:39:47.923 回答
1

CTE 更整洁(也许更有效),但你几乎拥有它。

select lch.ChequeID, lch.DateFa, lch.ChequeID
from LCheque lch
where lch.LChequeID = (select MAX(LChequeID) where ChequeID = lch.ChequeID)
于 2013-03-02T16:52:50.673 回答