在 Partition 上划分两行

Divide two rows over Partition

我有一个这样的table:

Id Sym sum_amount pair 
11  2    1000      1
11  3     500      1
22  4    200       2
22  4    50        2

而且我想将一对中的一个值除以同一对中的第二个值,通过 Id、Sym 进行分区。

并得到这些结果:

Id Sym sum_amount pair Div
11  2    1000      1    2
11  3    500       1   0.5
22  4    200       2    4
22  4    50        2   0.25

我想我需要这样的东西:

Ratio[???](Sum_Amount) Over (Partition by Id, Sym, pair)

有什么办法吗?我知道我可以对货币对、总和等进行平均,但我不知道如何计算这些比率?是否有内置的比率函数?

谢谢。

嗯。您需要 other 值作为除法。一种方法是获取 min()max() 并选择 other 一个:

select id, sum, sum_amount, pair,
       (case when max(sum_amount) over (partition by pair) = sum_amount
             then sum_amount / min(sum_amount) over (partition by pair)
             else sum_amount / max(sum_amount) over (partition by pair)
        end) as div
from t;

类似于 Gordon 的方法,但使用 CTE,避免整数除法并根据需要包含所有三列(我猜 Sym=3 是您的样本数据中的错字):

WITH CTE AS
(
    select id, Sym, sum_amount, pair, 
           minAmount = min(sum_amount) over (partition by Id, Sym, pair),
           maxAmount = max(sum_amount) over (partition by Id, Sym, pair),
           rMin = 1.0 * sum_amount / min(sum_amount) over (partition by Id, Sym, pair),
           rMax = 1.0 * sum_amount / max(sum_amount) over (partition by Id, Sym, pair)
   FROM t
)
SELECT id, Sym, sum_amount, pair,
       Div = CASE WHEN sum_amount = maxAmount THEN rMin ELSE rMax END
FROM CTE;

sql-Fiddle