获取给定日期 table 中的最新记录
Get the latest record in the table on a given day
我有一个 table A,其中包含列 offer_id、item_id 和 report_date(不是时间戳,只是日期)
我想获取给定日期特定 item_id 的 offer_id 的最新记录。我正在使用 Presto 数据库。有人可以帮忙吗?
我试过类似下面的东西,但不确定它是否 right.Still 学习。
select A.report_dt, A.offer_id, A.item_id
from table A
where A.rpt_dt = (select Max(rpt_dt)
from table
where item_id = A.item_id
and report_dt = date '2020-06-01')
order by item_id;
您可以使用 Window Functions 获取每个特定 item_id
的最新 offer_id
值,例如 RANK()
,如下所示:
SELECT offer_id, item_id
FROM
(
SELECT t.*,
RANK() OVER (PARTITION BY item_id
ORDER BY report_dt DESC) AS rnk
FROM tab t
) tt
WHERE tt.rnk = 1
其中 report_dt
值按降序排列 (ORDER BY report_dt DESC
) 对于子查询中的每个分组 item_id
(PARTITION BY item_id
)。
我有一个 table A,其中包含列 offer_id、item_id 和 report_date(不是时间戳,只是日期)
我想获取给定日期特定 item_id 的 offer_id 的最新记录。我正在使用 Presto 数据库。有人可以帮忙吗?
我试过类似下面的东西,但不确定它是否 right.Still 学习。
select A.report_dt, A.offer_id, A.item_id
from table A
where A.rpt_dt = (select Max(rpt_dt)
from table
where item_id = A.item_id
and report_dt = date '2020-06-01')
order by item_id;
您可以使用 Window Functions 获取每个特定 item_id
的最新 offer_id
值,例如 RANK()
,如下所示:
SELECT offer_id, item_id
FROM
(
SELECT t.*,
RANK() OVER (PARTITION BY item_id
ORDER BY report_dt DESC) AS rnk
FROM tab t
) tt
WHERE tt.rnk = 1
其中 report_dt
值按降序排列 (ORDER BY report_dt DESC
) 对于子查询中的每个分组 item_id
(PARTITION BY item_id
)。