假设 mssql 2005+,您可以使用 row_number 按用户分区并按活动日期排序。然后你只选择用户的第一行......
SELECT
*
FROM (
SELECT
USER_NAME,
CONVERT(nvarchar(20), ACTIVITY_DATE_TIME, 20) AS DATE_TIME,
WORK_TYPE, Location, ITEM, Quantity,
RN = row_number() over(paritition by USER_NAME order by activity_date_time DESC)
FROM
TRANSACTION_HISTORY
WHERE
USER_NAME in ('a_user','b_user','c_user','d_user','e_user')
) t
WHERE
t.RN = 1 --only want the top history per user
如果表真的很大,使用 apply 可能会更好,因为看起来您一次只需要为少数用户执行此操作...
SELECT
TTH.*
FROM
USER U
CROSS APPLY (
SELECT TOP 1
USER_NAME,
CONVERT(nvarchar(20), ACTIVITY_DATE_TIME, 20) AS DATE_TIME,
WORK_TYPE, Location, ITEM, Quantity
FROM
TRANSACTION_HISTORY TH
WHERE
TH.USER_NAME = U.USER_NAME
ORDER BY
activity_date_time DESC
) TTH
WHERE
U.USER_NAME in ('a_user','b_user','c_user','d_user','e_user')