views:

193

answers:

3

I have a table like this:

id| name  | attendence
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

+4  A: 
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.

Fosco
It is working.Thanks.
NAVEED
A: 

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.

Joseph
It is giving me only one record. Order By is applied after Group By here.
NAVEED
Yes, it is only giving you one record. That is what the LIMIT 1 is for. You stated you only wanted the last row. This will give you only the last row based on the id. If you still want all the rows returned, take off the phrase `LIMIT 1`.
Joseph
You did not understand my question. I want to get all groups but each group should be represented by last row of that group.
NAVEED
You are correct. I did misunderstand the question. `Fosco` appears to have the best answer imo.
Joseph
+1  A: 
SELECT MAX("id"), "name" FROM "test" WHERE "attendence" = 1 GROUP BY "name"
aib