开发者

SQL: GROUP BY records and then get last record from each group? [duplicate]

开发者 https://www.devze.com 2023-01-11 03:13 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: SQL Server: Only last entry in GROUP BY
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

SQL Server: Only last entry in GROUP BY

I have a table like this:

id| name  | attende开发者_JS百科nce
1 | Naveed| 1
2 | Naveed| 1
3 | Adil  | 1
4 | Adil  | 1

I use following query:

SELECT * FROM `test` WHERE `attendence`=1 GROUP BY name

The result with above query:

id| name   | attendence
3 | Adil   | 1
1 | Naveed | 1

Question:

Above result group rows by name but show first row from each group. I want to select last row(by id) from each group.

For example:

id| name   | attendence
2 | Naveed | 1
4 | Adil   | 1

How to write query for above result.

Thanks


SELECT a.* 
FROM test a 
WHERE a.attendence = 1 
AND NOT EXISTS (select 1 from test where name = a.name and id > a.id and attendence = 1)
GROUP BY name 

Might not even need the group by anymore.


SELECT MAX("id"), "name" FROM "test" WHERE "attendence" = 1 GROUP BY "name"


SELECT Name, Max(ID) FROM table WHERE attendance = 1 GROUP BY Name


Use the following query:

SELECT * FROM `test` WHERE `attendence`=1 GROUP BY name ORDER BY `id` DESC LIMIT 1

That will only select the row that meets the criteria with the highest id.

0

精彩评论

暂无评论...
验证码 换一张
取 消