我有下表。
| ID | 描述 | 進步 | 更新時間 |
|---|---|---|---|
| 1 | A B C D | 計劃 | 2022-04-20 10:00 |
| 1 | A B C D | 計劃 | 2022-04-25 12:00 |
| 1 | A B C D | 進行中 | 2022-04-26 下午 4:00 |
| 1 | A B C D | 進行中 | 2022-05-04 11:00 |
| 1 | A B C D | 進行中 | 2022-05-06 12:00PM |
我只想回傳具有最新 updated_time 的行,而不管它的進度如何,即,
| ID | 描述 | 進步 | 更新時間 |
|---|---|---|---|
| 1 | A B C D | 進行中 | 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)
我也收到以下錯誤,“尚不支持子查詢回傳的多個列”
uj5u.com熱心網友回復:
在子查詢中選擇多個值不起作用,您需要使用標量子查詢選擇單個值:
-- 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
輸出:
| ID | 描述 | 進步 | 更新時間 |
|---|---|---|---|
| 1 | A B C D | 進行中 | 2022-05-07 12:00:00.000 |
| 2 | A B C D | 進行中 | 2022-05-06 12:00:00.000 |
uj5u.com熱心網友回復:
您正在嘗試將單個值與多個列匹配,并且您會引發錯誤..
尋找您的目標代碼,而不是基于子查詢的 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
uj5u.com熱心網友回復:
我可能會為此使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476294.html
下一篇:自定義回傳MongoDB聚合
