4

I have a table like this :

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

And I would like to divide one value in a pair in the second in the same pair over partition by Id, Sym.

and get those results:

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

I think I will need something like this:

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

Any way to do this? I know that can I average over the pair, sum etc but I don't know how can I do those ratios? are there a built in function for ratio?

Thanks.

Haytem BrB
  • 1,528
  • 3
  • 16
  • 23
Jordan1200
  • 478
  • 1
  • 5
  • 20

2 Answers2

4

Hmmm. You need the other value for the division. One method is to get the min() and max() and choose the other one:

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 Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

Similar to Gordon's approach but using a CTE, avoiding integer division and including all three columns as desired (i guess Sym=3 was a typo in your sample data):

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

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939