在 DB2/400 中获取仅按用户分组的最新结果
Posted
技术标签:
【中文标题】在 DB2/400 中获取仅按用户分组的最新结果【英文标题】:Getting latest of many results only grouped by user in DB2/400 【发布时间】:2019-10-07 18:29:42 【问题描述】:我正在发布我的查询和结果,但我试图将其限制为仅由创建者提供的最新状态和时间戳。
select t2.creator, t1.event_id, t2.status, max(t2.createdTS)
from schema.event T1
inner join schema.event_to_event_statust T2
on t1.event_id = t2.event_id
group by t2.creator, t1.event_id, t2.status;
creator | event_id | status | createdTS
-----------------------------------------------------
123 1 New 2019-01-29 17:27:50.899408
123 1 Live 2019-01-29 17:29:50.899408
123 1 Closed 2019-01-29 17:45:50.899408
456 5 New 2019-01-29 17:32:50.899408
456 5 Live 2019-01-29 17:48:50.899408
我想要的这组结果实际上是
creator | event_id | status | createdTS
-----------------------------------------------------
123 1 Closed 2019-01-29 17:45:50.899408
456 5 Live 2019-01-29 17:48:50.899408
所以我应该每个创作者只有一行,它应该是最新的记录。我做错了什么?
【问题讨论】:
另外,我的问题在没有评论/解释的情况下被否决,但无论如何。 真的需要加入吗? 是的,这是我获取用户状态的唯一方法 状态从t2中选择 【参考方案1】:以下是否在您的 IBM i 上“按原样”工作?
WITH RES (creator, event_id, status, createdTS) AS
(
VALUES
(123, 1, 'New', TIMESTAMP('2019-01-29 17:27:50.899408'))
, (123, 1, 'Live', TIMESTAMP('2019-01-29 17:29:50.899408'))
, (123, 1, 'Closed', TIMESTAMP('2019-01-29 17:45:50.899408'))
, (456, 5, 'New', TIMESTAMP('2019-01-29 17:32:50.899408'))
, (456, 5, 'Live', TIMESTAMP('2019-01-29 17:48:50.899408'))
)
SELECT creator, event_id, status, createdTS
FROM
(
SELECT creator, event_id, status, createdTS
, ROWNUMBER() OVER (PARTITION BY creator ORDER BY createdTS desc) AS rn
FROM RES
) T
WHERE RN=1;
如果不是,那么您的 IBM i 版本和修改是什么?
【讨论】:
【参考方案2】:试试
with temp as (
select t2.creator, t1.event_id, t2.status, t2.createdTS
row_number() over (partition by t2.creator order by t2.createdTS desc) as rownum
from schema.event T1
inner join schema.event_to_event_statust T2
on t1.event_id = t2.event_id
group by t2.creator, t1.event_id, t2.status
)
select creator, event_id, status, createdTS
from temp
where rownum = 1
@MarkBarinstein:感谢 SQL 更正
另一种可能是
select t2.creator, t1.event_id, t2.status, t2.createdTS
from event T1
inner join event_to_event_status T2
on t1.event_id = t2.event_id
INNER JOIN (select event_id, creator, max(createdts) AS createdts
FROM event_to_event_status
GROUP BY event_id, creator) AS x
ON t2.event_id = x.event_id AND t2.creator = x.creator AND t2.createdts = x.createdts
抱歉,我没有 iSeries 可以试用
【讨论】:
好的,所以我必须修复它以将 row_number 用于我的带有 iseries 7 的 db2 版本,但我仍然得到Token PARTITION was not valid, valid tokens:)
以上是关于在 DB2/400 中获取仅按用户分组的最新结果的主要内容,如果未能解决你的问题,请参考以下文章