简体   繁体   English

Mysql-如何使用GROUP BY获取最后一条记录

[英]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:- 使用子查询获取每个deptid的最大ID,然后将其与表结合在一起,可以得到如下信息:

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). 使用GROUP_CONCAT的另一种可能的解决方案,尽管并不热衷于此(如果last_activity包含用于GROUP_CONCAT的定界符,它将失败。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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