Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since you are on SQL Server 2012... here is a version that uses that. It might be faster than other solutions but you have to test that on your data.</p> <p><code>sum() over()</code> will do a running sum ordered by <code>Id</code> adding <code>1</code> when there are a value in the column and keeping the current value for <code>null</code> values. The calculated running sum is then used to partition the result in <code>first_value() over()</code>. The first value ordered by <code>Id</code> for each "group" of rows generated by the running sum has the value you want.</p> <pre><code>select T.Id, first_value(T.FeeModeId) over(partition by T.NF order by T.Id rows between unbounded preceding and current row) as FeeModeId, first_value(T.Name) over(partition by T.NS order by T.Id rows between unbounded preceding and current row) as Name, T.Amount from ( select Id, FeeModeId, Name, Amount, sum(case when FeeModeId is null then 0 else 1 end) over(order by Id) as NF, sum(case when Name is null then 0 else 1 end) over(order by Id) as NS from YourTable ) as T </code></pre> <p><a href="http://sqlfiddle.com/#!6/a5213/2">SQL Fiddle</a></p> <p>Something that will work pre SQL Server 2012:</p> <pre><code>select T1.Id, T3.FeeModeId, T2.Name, T1.Amount from YourTable as T1 outer apply (select top(1) Name from YourTable as T2 where T1.Id &gt;= T2.Id and T2.Name is not null order by T2.Id desc) as T2 outer apply (select top(1) FeeModeId from YourTable as T3 where T1.Id &gt;= T3.Id and T3.FeeModeId is not null order by T3.Id desc) as T3 </code></pre> <p><a href="http://sqlfiddle.com/#!6/a5213/1">SQL Fiddle</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload