在分区上划分两行

时间:2016-02-11 12:57:28

标签: sql sql-server partition

我有一张这样的表:

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)

有什么办法吗?我知道我可以平均对,总和等但我不知道我怎么能做那些比率?是否有比例的内置功能?

感谢。

2 个答案:

答案 0 :(得分:3)

嗯。您需要该部门的其他值。一种方法是获取min()max()并选择其他

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;

答案 1 :(得分:0)

类似于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