简体   繁体   中英

Mysql - How to get last record using GROUP BY

I have a table like below:

id   |   deptid   |   last_activities
1    |     1      |   MMD PURCASHING
2    |     1      |   JKO / REPORTING
3    |     2      |   STAND BY CC
4    |     3      |   JKO / REPORTING

My query:

SELECT id, deptid, last_activities FROM dept_activities GROUP BY deptid ORDER BY id DESC

And the result like below:

id   |   deptid   |   last_activities
4    |     3      |   JKO / REPORTING
3    |     2      |   STAND BY CC
1    |     1      |   MMD PURCASHING

There i want result like this:

id   |   deptid   |   last_activities
4    |     3      |   JKO / REPORTING
3    |     2      |   STAND BY CC
2    |     1      |   JKO / REPORTING

How could it be? How right query?

Please try this :

SELECT * FROM dept_activities AS da1
JOIN
(SELECT MAX(id) as max_id FROM dept_activities GROUP BY deptid DESC) AS da2
ON (da1.id = da2.max_id);

Using a sub query to get the max id for each deptid, and then joining that against the table gives you something like this:-

SELECT a.id, a.deptid, a.last_activities
FROM dept_activities a
INNER JOIN
(
    SELECT MAX(id) AS MaxId, deptid
    FROM dept_activities 
    GROUP BY deptid 
) Sub1
ON a.deptid = Sub1.deptid
AND a.id = Sub1.MaxId
ORDER BY a.id DESC

Another possible solution using GROUP_CONCAT, although not keen on this (and will fail if last_activity contains the delimiter you use for GROUP_CONCAT).

SELECT MAX(id), deptid, SUBSTRING_INDEX(GROUP_CONCAT(last_activities ORDER BY id DESC), ',', 1)
FROM dept_activities 
GROUP BY a.deptid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM