How to add row in SQL if value from one column is greater than the value in another column

时间:2019-04-23 15:05:48

标签: sql-server

An example of my dataset would be:

ZoneA: 0-100

ZoneB: 100-200

Name  SubName  startValueA  endValueA  startValueB  endValueB
A     X        0            25         0            100
A     X        25           35         0            100 
A     X        35           80         0            100 
A     X        80           95         0            100 
A     X        95           120        0            100 
A     Y        120          145        100          200 
A     Y        145          160        100          200 
A     Y        160          175        100          200 
A     Y        175          190        100          200 
A     Y        190          200        100          200 

Essentially what I'm desiring is this:

Name  SubName  startValueA  endValueA  startValueB  endValueB  Percent
A     X        0            25         0            100        1
A     X        25           35         0            100        1
A     X        35           80         0            100        1    
A     X        80           95         0            100        1    
A     X        95           100        0            100        .2   <--- (100-95)/(120-95)
A     X        100          120        100          200        .8   <--- (120-100)/(120-95)
A     Y        120          145        100          200        1    
A     Y        145          160        100          200        1 
A     Y        160          175        100          200        1
A     Y        175          190        100          200        1
A     Y        190          200        100          200        1

So a row is added where ValueA crosses over ValueB, and then the resulting percent of each is calculated. Basically I'm trying to figure out how much of valueA belongs in each Zone as defined by valueB. I have the first row done pretty simply with something along the lines of:

case 
   when endValueA <= endValueB then 1 
   else ((endValueB - startValueA)/(endValueA - startValueA))

I'm just not sure how to get the additional row added in with the inverse percent.

Thanks in advance for the help!

0 个答案:

没有答案