Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Following <code>CTE</code> returns your given output for your given inputs. You can use these results as a starting point for inserting the records into another table.</p> <p>The gist of it is </p> <ul> <li>Use a recursive <code>CTE</code>, starting with all rows where <code>rn=1</code>.</li> <li>In the recursive part, pick <code>Data1-3</code> from the recursive part if available, otherwise retain the exisiting value (<code>COALESCE</code>). The result of the <code>CTE</code> now is your final values + the initial values where <code>rn=1</code></li> <li>Add a <code>ROW_NUMBER</code> for each <code>userID</code> but <code>ORDER DESC</code> on the existing <code>rn</code>. This makes sure that the <em>latest</em> values get rownumber 1.</li> <li>Finally select all with rownumber 1 and add another rownumber as per your final results.</li> </ul> <p><strong>SQL Statement</strong></p> <pre><code>;WITH q AS ( SELECT rn , UserID , Data1 , Data2 , Data3 FROM Inherited WHERE rn = 1 UNION ALL SELECT i.rn , i.UserID , COALESCE(i.Data1, q.Data1) , COALESCE(i.Data2, q.Data2) , COALESCE(i.Data3, q.Data3) FROM q INNER JOIN Inherited i ON i.rn = q.rn+1 AND i.userID = q.userID ) SELECT rn = ROW_NUMBER() OVER (ORDER BY userID) , * FROM ( SELECT UserID , Data1 , Data2 , Data3 , rn = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY rn DESC) FROM q ) t WHERE rn = 1 </code></pre> <p><strong>Test Script</strong></p> <pre><code>;WITH Inherited (rowID, rn, userID, Data1, Data2, Data3) AS ( SELECT * FROM (VALUES (1, 1, 1, 'A', null, '123') , (2, 2, 1, 'B', '111', null) , (3, 1, 2, 'C', '222', '333') , (4, 2, 2, 'D', null, null) , (5, 3, 2, 'E', '111', null) , (6, 1, 3, 'F', '333', '222') ) a (b, c, d, e, f, g) ) , q AS ( SELECT rn , UserID , Data1 , Data2 , Data3 FROM Inherited WHERE rn = 1 UNION ALL SELECT i.rn , i.UserID , COALESCE(i.Data1, q.Data1) , COALESCE(i.Data2, q.Data2) , COALESCE(i.Data3, q.Data3) FROM q INNER JOIN Inherited i ON i.rn = q.rn+1 AND i.userID = q.userID ) SELECT rn = ROW_NUMBER() OVER (ORDER BY userID) , * FROM ( SELECT UserID , Data1 , Data2 , Data3 , rn = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY rn DESC) FROM q ) t WHERE rn = 1 </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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