在Presto SQL中使用Max()函数于Where子句

3
我有以下表格。
ID 描述 进度 更新时间
1 abcd 计划中 2022-04-20 10:00AM
1 abcd 计划中 2022-04-25 12:00AM
1 abcd 进行中 2022-04-26 4:00PM
1 abcd 进行中 2022-05-04 11:00AM
1 abcd 进行中 2022-05-06 12:00PM
我只想返回具有最新更新时间的行,而不管它处于什么状态,如下所示,
ID 描述 进度 更新时间
1 abcd 进行中 2022-05-06 12:00PM
我知道如果按“进度”分组(如下所示),我也会得到一个计划中的结果,但我不需要它。我只需要每个ID的单行及其最新更新时间。
我编写了以下查询:
select ID,desc,progress,updated_time 
from t1 
where updated_time IN (select ID, desc, progress, max(updated_time) 
from t1 group by 1,2,3)

我也遇到了以下错误:'子查询返回的多列尚不支持'。
3个回答

3

在子查询中选择多个值是行不通的,你需要使用标量子查询选择单个值:

-- 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 窗口函数和子查询的类似方法:

--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

输出:

编号 描述 进度 更新时间
1 abcd 进行中 2022-05-07 12:00:00.000
2 abcd 进行中 2022-05-06 12:00:00.000

1
他们都起作用了!非常感谢你! - Mupp

1
我会使用row_number或其他排名函数来处理这个问题。
with t as (select a.*,
 row_number() over (partition by id order by updated_time desc as rn) 
select * from t where rn = 1

0

你正在尝试将单个值与多个列进行匹配,这会引发错误...

为了实现你的目标,建议你使用内连接而不是基于子查询的IN语句。

select ID,desc,progress,updated_time 
from t1 
INNER JOIN 
( select ID, desc, progress, max(updated_time) max_time 
from t1 group by 1,2,3) t on t.max_time = t1.updated_time

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接