我整個下午都在嘗試洗掉一個看起來像這樣的表:
ID1 | ID2 | Date | Time |Status | Price
---- ----- ------------ ----------------- -------- -------
01 | A | 01/01/2022 | 10:41:47.000000 | DDD | 55
01 | B | 02/01/2022 | 16:22:31.000000 | DDD | 53
02 | C | 01/01/2022 | 08:54:03.000000 | AAA | 72
02 | D | 03/01/2022 | 11:12:35.000000 | DDD |
03 | E | 01/01/2022 | 17:15:41.000000 | DDD | 67
03 | F | 01/01/2022 | 19:27:22.000000 | DDD | 69
03 | G | 02/01/2022 | 06:45:52.000000 | DDD | 78
基本上,我需要根據兩個條件進行重復資料洗掉:
Status:其中 AAA > BBB > CCC > DDD。所以,選擇最高的一個。- 當 與
Status相同時ID1,根據Date和選擇最新的Time。
決賽桌應如下所示:
ID1 | ID2 | Date | Time |Status | Price
---- ----- ------------ ----------------- -------- -------
01 | B | 02/01/2022 | 16:22:31.000000 | DDD | 53
02 | C | 01/01/2022 | 08:54:03.000000 | AAA | 72
03 | G | 02/01/2022 | 06:45:52.000000 | DDD | 78
有沒有辦法在 Redshift SQL / PostgreSQL 中做到這一點?
我嘗試了這個的變體,但每次它都不起作用,因為它要求我將所有列添加到組中,所以它就達不到目的
select a.id1,
b.id2,
b.date,
b.time,
b.status,
b.price,
case when (status = 'AAA') then 4
when (status = 'BBB') then 3
when (status= 'CCC') then 2
when (status = 'DDD') then 1
when (status = 'EEE') then 0
else null end as row_order
from table1 a
left join table2 b
on a.id1=b.id1
group by id1
having row_order = max(row_order)
and date=max(date)
and time=max(time)
任何幫助都將不勝感激!
uj5u.com熱心網友回復:
視窗函式擅長于此:
SELECT ID1, ID2, Date, Time, Status, Price
FROM (
SELECT *,
row_number() OVER (PARTITION BY ID1 ORDER BY Status, Date DESC, Time DESC) rn
FROM MyTable
) t
WHERE rn = 1
在這里看到它的作業:
https://dbfiddle.uk/uAvDz1Qn
uj5u.com熱心網友回復:
你可以ROW_NUMBER()這樣使用:
with cte as (
select a.id1,
b.id2,
b.date,
b.time,
b.status,
b.price,
ROW_NUMBER() OVER (PARTITION BY a.id1 ORDER BY b.status ASC, b.date DESC, b.time DESC) RN
from table1 a
left join table2 b on a.id1=b.id1
)
select * from cte where rn = 1
uj5u.com熱心網友回復:
這是一個典型的 top-1-per-group 問題。正如 Joel Coehoorn 和 Aaron Dietz 所證明的,規范解決方案確實涉及視窗函式。
但是 Postgres 有一個特定的擴展,稱為distinct on,它正是為解決 top-1-per-group 問題而構建的。語法更簡潔,并且您受益于內置優化:
select distinct on (id1) t.*
from mytable t
order by id1, status, "Date" desc, "Time" desc
這是一個基于 Joel Coehoorn 的DB Fiddle 演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526451.html
上一篇:函式current_user
