繁体   English   中英

根据相互时间戳列和动作时间戳列获取最新行

[英]Get latest row based on mutual timestamp column and action timestamp column

如何根据操作时间戳(唯一)和通用时间戳(INDSTY_RPT_TMSTMP)检索最近的操作时间戳行。 结果应该每个 INDSTY_RPT_TMSTMP 行只有 1 行。

数据集: 在此处输入图像描述

预期结果: 在此处输入图像描述

说明

对于此相互时间戳 (2020-08-11-18.55.15.100000),最新操作是 (2020-08-12-14.56.52.545822)。

对于此相互时间戳 (2020-08-11-18.50.15.100000),最新操作是 (2020-08-12-15.05.13.168624)。

对于此相互时间戳 (2020-08-11-18.45.15.100000),最新操作是 (2020-08-12-12.49.39.880529)。

它们按 indsty_rpt_tmstmp desc、rpt_chg_tmstmp 排序

我正在尝试这个,但它不起作用:

SELECT INDSTY_RPT_ID, INDSTY_RPT_ID_TP_CD, INDSTY_RPT_TMSTMP, max(RPT_CHG_TMSTMP),
INDSTY_RPT_STS_CD, INDSTY_RPT_STS_TP_CD, HTTP_RESP_CD, HTTP_RESP_DESC, APP_RESP_CD, APP_RESP_DESC 
FROM table
where indsty_rpt_id = 'Hfhs731'
group by INDSTY_RPT_ID, INDSTY_RPT_ID_TP_CD, INDSTY_RPT_TMSTMP, RPT_CHG_TMSTMP,
INDSTY_RPT_STS_CD, INDSTY_RPT_STS_TP_CD, HTTP_RESP_CD, HTTP_RESP_DESC, APP_RESP_CD, APP_RESP_DESC 
order by indsty_rpt_tmstmp desc, rpt_chg_tmstmp desc

一种方法是相关子查询:

select t.*
from t
where t.rpt_chg_tmstmp = (select max(t2.rpt_chg_tmstmp)
                          from t t2
                          where t2.INDSTY_RPT_ID  = t.INDSTY_RPT_ID 

和 t2.indsty_rpt_tmstmp = t.indsty_rpt_tmstmp );

For MySQL 8.0+ you can use a window function to assign a sequential number sorted by the timestamp in descending order and select the most recent. 例如:

SELECT *
FROM 
(
  SELECT *,
  ROW_NUMBER() OVER(PARTITION BY indsty_rpt_tmstmp ORDER BY rpt_chg_tmstmp DESC) AS row_num
  FROM t
  
) t1
WHERE row_num = 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM