在子查询中 Select 多个值将不起作用,您需要使用scalar subquery Select 单个值:
-- sample data
WITH dataset (ID, Desc, progress, updated_time) AS (
VALUES
(1, 'abcd', 'planned', timestamp '2022-04-20 10:00'),
(1, 'abcd', 'planned', timestamp '2022-04-25 12:00'),
(1, 'abcd', 'in progress', timestamp '2022-04-26 16:00'),
(1, 'abcd', 'in progress', timestamp '2022-05-04 11:00'),
(1, 'abcd', 'in progress', timestamp '2022-05-06 12:00'),
(1, 'abcd', 'in progress', timestamp '2022-05-07 12:00'),
(2, 'abcd', 'in progress', timestamp '2022-05-04 11:00'),
(2, 'abcd', 'in progress', timestamp '2022-05-06 12:00')
)
--query
select id, Desc, progress, updated_time
from dataset o
where updated_time = (select max(updated_time) from dataset i where i.id = o.id)
或具有max
窗口功能和子 Select 的类似方法:
--query
select id, Desc, progress, updated_time
from (
select *, max(updated_time) over (partition by id) max_time
from dataset
)
where max_time = updated_time
或仅使用row_number
:
select id, Desc, progress, updated_time
from
(
select *,
row_number() over(partition by id order by updated_time desc) rank
from dataset
)
where rank = 1
输出:
id |
Desc |
progress |
updated_time |
1 |
abcd |
in progress |
2022-05-07 12:00:00.000 |
2 |
abcd |
in progress |
2022-05-06 12:00:00.000 |