Group by and get the last row

一曲冷凌霜 提交于 2019-12-13 04:47:37

问题


When I used the

SELECT * FROM reports WHERE staff='$username' GROUP BY taskid

on my query, I get a result of the first row from that group.

What do I need to add to get the result from the last row of that group?

last row means having id greater than the other row from that group.

I tried adding

ORDER BY id DESC 

or

ORDER BY id

but it did not return the intended result.


回答1:


You are using a group by function without any aggregate functions. You probably want to do an order by instead (No group by in the query):

SELECT * FROM reports WHERE staff='$username' order BY taskid desc;

Group By functions are commonly used when you want to use an aggregate function on a particular column (such as get an average row value, or a sum) and the like. If you are not using any aggregate function, then using Group By will not do anything.

If you only want to get one row from the query you can add a limit clause like this:

SELECT * FROM reports WHERE staff='$username' order BY taskid desc limit 1;



回答2:


if you want the "last" row per group, then you need to specify which field defines uniqueness (i.e. what you mean by "first/last row") and then isolate those rows in a subquery.

e.g.

this gets you the max(id) for each group

SELECT taskid, max(id) as max_id FROM reports 
WHERE staff ='$username' 
GROUP BY taskid

and this gets the entire row(s):

select * from reports where id 
in
(
    SELECT max(id) as max_id FROM reports 
    WHERE staff='$username' 
    GROUP BY taskid
) x

This of course assumes that id is unique and assigned in ascending order and that therefore max(id) indicates the last row per group.

Alternatively you could rewrite this using a join:

select * from reports r
inner join
(
    SELECT max(id) as max_id FROM reports 
    WHERE staff='$username' 
    GROUP BY taskid
) x
on r.id = x.max_id


来源:https://stackoverflow.com/questions/12368974/group-by-and-get-the-last-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!