I am new to snowflake and I am trying to run an sql query that would extract the maximum Datetime for each ID. Below is a sample of my data
Table name: final_extract
| id | datetime | ip |
|---|---|---|
| 111 | 2022-02-03 11:37:58:000 | 62.44.134.97 |
| 222 | 2021-02-03 11:37:58:000 | 88.44.134.96 |
| 111 | 2022-02-01 11:37:58:000 | 22.44.134.97 |
| 111 | 2021-02-03 11:37:58:000 | 69.44.134.97 |
what I want to achieve
| id | datetime | ip |
|---|---|---|
| 111 | 2022-02-03 11:37:58:000 | 62.44.134.97 |
| 222 | 2021-02-03 11:37:58:000 | 88.44.134.96 |
The code below doesn't seem to achieve what I want.
select "id", MAX("datetime") As LastLoginDateTime, "ip "
from final_extract
group by "id ","ip "
order by MAX("datetime") DESC
limit 10
CodePudding user response:
Your query doesn't work because you have a different ip for each row, you have to decide which to choose. Check it out, I choose the last value from ip:
SELECT DISTINCT id
, MAX(datetime) OVER(PARTITION BY id) As LastLoginDateTime
, LAST_VALUE(ip) OVER(PARTITION BY id ORDER BY datetime) AS ip
FROM final_extract
ORDER BY LastLoginDateTime DESC
LIMIT 10;
