I am trying to query a table by taking the maximum values from two different date columns, and output's all the records that have maximum of both the dates
The table has 6 columns which include st_id(string)(there are multiple entries of the same id), as_of_dt(int) and ld_dt_ts(timestamp). From this table, I am trying to get the max value of as_of_dt and ld_dt_ts and group by st_id and display all the records.
This works perfectly, but its not really optimal
SELECT A.st_id, A.fl_vw, A.tr_record FROM db.tablename A
INNER JOIN (
SELECT st_id, max(as_of_dt) AS as_of_dt, max(ld_dt_ts) AS ld_dt_ts
From db.tablename
group by st_id
) B on A.st_id = B.st_id and A.as_of_dt = B.as_of_dt and A.ld_dt_ts= B.ld_dt_ts
--
The expected result should return the st_id that has the maximum of both as_of_dt and ld_dt_ts i.e., which will be the latest record for each st_id.