Q:

MSSQL - get the value of the first bigger value in a field in another table

A query returns the following resultset from tableA:
Condition   Ranking
Cell        103
Cell        142
CM          124
ECM         423
CM          105
ECM         404

On a separate tableB I have values with an increasing sum for both the above 3 conditions as shown below:
Condition   Bins    IncreasingSum
Cell        Bin1    0
Cell        Bin2    1
Cell        Bin3    1
Cell        Bin4    10
Cell        Bin5    36
Cell        Bin6    94
Cell        Bin7    223
....        ....    ...
ECM         Bin1    2
ECM         Bin2    4
ECM         Bin3    11
ECM         Bin4    34
ECM         Bin5    77
ECM         Bin6    166
ECM         Bin7    326
ECM         Bin8    540
ECM         Bin9    843
....        ....    ....
CM          Bin1    2
CM          Bin2    12
CM          Bin3    35
CM          Bin4    114
CM          Bin5    233
CM          Bin6    429

I would like to join these tables and get the name of the Bin with the first bigger value than the ranking in which the condition belongs to. More specifically a result as shown below:
Condition   Ranking    Bin
Cell        103        Bin7
Cell        142        Bin7
CM          124        Bin5
ECM         423        Bin8
CM          105        Bin4
ECM         404        Bin8

Any suggestions please?

A:

You can use apply:
select a.*, b.bin
from tableA a outer apply
     (select top (1) b.bin
      from tableB b
      where b.condition = a.condition and
            b.increasingsum > a.ranking
      order by b.increasingsum asc
     ) b;

