找到Person的最后一条记录

时间:2013-08-03 10:08:06

标签: sql

这是我的数据

Id Name Amt

1  ABC  20
2  XYZ  30
3  ABC  25
4  PQR  50
5  XYZ  75
6  PQR  40

我想要每个特定名字的最后一条记录,如:

3  ABC  25
5  XYZ  75 
6  PQR  40

我尝试过分组,但我遗漏了一些东西。

SELECT     PatientID, Balance, PReceiptNo
FROM         tblPayment
GROUP BY PatientID, Balance, PReceiptNo

5 个答案:

答案 0 :(得分:6)

这样的事情应该有效:

SELECT p1.*
FROM tblPayment p1
LEFT JOIN tblPayment p2 ON p1.Name = p2.Name AND p1.Id < p2.Id
WHERE p2.Id IS NULL;

请参阅this SQLFiddle

答案 1 :(得分:1)

应该类似于:

SELECT 
    id, 
    name, 
    amt
FROM
    myTable mt1
where mt1.id = (
                    SELECT 
                        MAX(id) 
                    FROM myTable mt2 
                    WHERE mt2.name = mt1.name
                )

答案 2 :(得分:0)

这应该有效

select * from (select id, name,amount from test order by id desc)as t1 group by name;

fiddle

答案 3 :(得分:0)

还有一个选择

SELECT *
FROM tblPayment p1
WHERE EXISTS (
              SELECT 1
              FROM tblPayment p2
              WHERE p1.Name = p2.Name
              HAVING MAX(p2.Id) = p1.Id
              )

请参阅SQLFiddle

上的演示

答案 4 :(得分:0)

可能的解决方案:

Select p.* 
from tblPayment p
Inner join ( 
  Select name, max(id) as id
  From tblPayment 
  Group by name
) as latest on latest.id = p.id