2

这是我的数据

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
4

5 回答 5

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;

看到这个 SQLFiddle

于 2013-08-03T10:12:41.410 回答
1

应该类似于:

SELECT 
    id, 
    name, 
    amt
FROM
    myTable mt1
where mt1.id = (
                    SELECT 
                        MAX(id) 
                    FROM myTable mt2 
                    WHERE mt2.name = mt1.name
                )
于 2013-08-03T10:15:03.507 回答
0

另一种选择

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

见演示SQLFiddle

于 2013-08-03T19:49:53.213 回答
0

这应该工作

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

小提琴

于 2013-08-03T10:35:18.207 回答
0

A possible solution:

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
于 2013-08-03T22:56:55.890 回答