I have a table called "history" with some sample data below:
SITE_ID TARGET_PRIMARY_KEY TARGET_TABLE UPDATED_AT USER_ID
1 1025test 4 2018/10/25 12:01 e4
1 1025test 4 2018/10/25 12:02 e1
1 1025test 4 2018/10/25 12:03 e2
1 1025test 4 2018/10/25 12:04 e3
1 aaa 4 2018/10/19 15:01 e1
5 aaa 7 2018/10/19 15:02 e2
1 aaa 4 2018/10/19 15:03 e3
1 aaa 4 2018/10/19 15:04 e4
1 aaa 4 2018/10/19 15:05 e5
1 aaa 4 2018/10/19 15:06 e6
What I want to achieve is:
For each unique combination of "SITE_ID"
and "TARGET_PRIMARY_KEY"
, pick up the record that has the greatest (latest) value of "UPDATED_AT"
and also make sure the corresponding "USER_ID"
is correct.
Expecting result is:
1 1025test 4 2018/10/25 12:04 e3
1 aaa 4 2018/10/19 15:06 e6
I have tried the following sql:
SELECT
hist.SITE_ID AS siteId,
TARGET_PRIMARY_KEY AS skey,
hist.TARGET_TABLE AS targetTable,
MAX(UPDATED_AT) AS lastActionDate,
hist.USER_ID
FROM
history AS hist
WHERE
hist.TARGET_TABLE = 4
AND hist.SITE_ID = 1
GROUP BY TARGET_PRIMARY_KEY
However, the "USER_ID"
information seems not synced with the "UPDATED_AT"
I got:
1 1025test 4 2018/10/25 12:04 e4
Can somebody please give me some advise? Thanks.