问题:
在包含多行考勤的表中对于用户数据,目标是仅获取每个用户的最后一次出勤值,按用户 ID 分组。但是,使用带有 order 子句的 GROUP BY 不会返回所需的结果。
要仅选择最后一个出勤值,请使用以下方法:
<code class="sql">SELECT id_member, MAX(timestamp) AS last_timestamp, attendance FROM view_event_attendance WHERE id_event = 782 GROUP BY id_member ORDER BY last_timestamp DESC;</code>
<code class="sql">SELECT id_branch_channel, id_member, attendance, timestamp, id_member FROM view_event_attendance WHERE (id_member, last_timestamp) IN ( SELECT id_member, MAX(timestamp) AS last_timestamp FROM view_event_attendance WHERE id_event = 782 GROUP BY id_member ORDER BY last_timestamp DESC );</code>
<code class="sql">SELECT id_branch_channel, id_member, attendance, timestamp, id_member FROM view_event_attendance AS t1 WHERE timestamp = (SELECT MAX(timestamp) FROM view_event_attendance AS t2 WHERE t1.id_member = t2.id_member AND t1.id_event = t2.id_event);</code>
注意:此解决方案避免使用带有 ORDER BY 子句的 GROUP BY,这对于大型表来说效率低下。
以上是如何使用 MySQL 仅选择分组表中的最后一个值?的详细内容。更多信息请关注PHP中文网其他相关文章!