問題:
在包含多行考勤的表中對於用戶數據,目標是僅獲取每個用戶的最後一次出勤值,按用戶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中文網其他相關文章!