Problem:
In a table containing multiple rows of attendance data for users, the goal is to obtain only the last attendance value for each user, grouped by user ID. However, using GROUP BY with order clauses does not return the desired result.
To select only the last attendance value, use the following approach:
<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>
Note: This solution avoids using GROUP BY with ORDER BY clauses, which can be inefficient for large tables.
The above is the detailed content of How to Select Only the Last Value in a Grouped Table Using MySQL?. For more information, please follow other related articles on the PHP Chinese website!