以下是我的一个子查询的输出。我陷入了困境。
ID | Principal | Price | Difference
102522 | 47000 | 99.9285 |
102522 | 47000 | 100.6801 |
102522 | 47000 | 99.9285 |
102522 | 47000 | 100.6801 |
102522 | 47000 | 99.9285 |
102522 | 47000 | 100.6801 |
1048798 | 280000 | 102.3823 |
1048798 | 280000 | 102.3666 |
1048798 | 280000 | 102.3823 |
1048798 | 280000 | 102.3666 |
1048798 | 280000 | 102.3823 |
1048798 | 280000 | 102.3666 |
1048798 | 280000 | 102.7026 |
我想填充列差异。
应该是给定ID的MAX价格与特定ID的价格之间的差异。
例如。
ID | Principal | Price | Difference
102522 | 47000 | 99.9285 | 100.6801 - 99.9285
102522 | 47000 | 100.6801 | 100.6801 - 100.6801
102522 | 47000 | 99.9285 | 100.6801 - 99.9285
102522 | 47000 | 100.6801 | 100.6801 - 100.6801
102522 | 47000 | 99.9285 | 100.6801 - 99.9285
102522 | 47000 | 100.6801 | 100.6801 - 100.6801
1048798 | 280000 | 102.3823 |
1048798 | 280000 | 102.3666 |
1048798 | 280000 | 102.3823 |
1048798 | 280000 | 102.3666 |
1048798 | 280000 | 102.3823 |
1048798 | 280000 | 102.3666 |
1048798 | 280000 | 102.7026 |
我会理解如何进行的任何指示?
答案 0 :(得分:4)
你想要的是最大化的窗口功能。 MAX(Price) OVER (PARTITION BY ID)
会为您提供每行每个ID的最高价格,然后您只需减去该行的价格,因此您的对帐单就是这样的
Select ID, Pricipal, Price, MAX(Price) OVER (PARTITION BY ID) - Price AS Difference
FROM (subquery)
答案 1 :(得分:3)
只需使用窗口功能:
select t.*,
(max(t.price) over (partition by t.id) - t.price) as difference
from t;