Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try something like this - just a couple of correlated sub-queries enforcing all the rules. First sub-query is finding all dates smaller then current and second one is eliminating values after the newest LoanedMoney = 0. Select MIN from it, and use COALESCE to replace it with current date if it's null.</p> <pre><code>UPDATE z1 SET LoanedDate = CASE WHEN LoanedMoney = 0 THEN NULL ELSE COALESCE ( (SELECT MIN(DATE) FROM DBNAME z2 WHERE z1.Customer_ID = z2.Customer_ID AND z1.Document_ID = z2.Document_ID AND z2.Date &lt; z1.Date AND z2.Date &gt; (SELECT MAX(DATE) FROM dbo.DBNAME z3 WHERE z3.Customer_ID = z2.Customer_ID AND z3.Document_ID = z2.Document_ID AND z3.Date &lt; z1.Date AND z3.LoanedMoney = 0) ), Date) END FROM dbo.DBNAME z1 </code></pre> <p><strong><a href="http://sqlfiddle.com/#!6/cdde1/1" rel="nofollow">SQLFiddle DEMO</a></strong></p> <p><strong>EDIT - Option2</strong></p> <p>Here is another method, using different concepts like <a href="http://technet.microsoft.com/en-us/library/ms186734.aspx" rel="nofollow"><code>ROW_NUMBER()</code></a> function and <a href="http://technet.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx" rel="nofollow">recursive CTE</a>. Might be a bit harder to understand, but it will outperform the first query on larger tables.</p> <pre><code>WITH CTE_Prep AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Document_ID, Customer_ID ORDER BY [DATE]) RN FROM DBNAME ) ,RCTE AS ( SELECT *, CASE WHEN LoanedMoney&gt;0 THEN Date END AS LoanedDate2 FROM CTE_Prep WHERE RN = 1 UNION ALL SELECT p.*, CASE WHEN p.LoanedMoney=0 THEN NULL ELSE CASE WHEN r.LoanedDate2 IS NULL THEN p.Date ELSE r.LoanedDate2 END END AS LoanedDate2 FROM CTE_Prep p INNER JOIN RCTE r ON p.Customer_ID = r.Customer_ID AND p.Document_ID = r.Document_ID AND p.RN = r.RN + 1 ) UPDATE z SET z.LoanedDate = r.LoanedDate2 FROM RCTE r INNER JOIN dbo.DBNAME z ON r.Customer_ID = z.Customer_ID AND r.Document_ID = z.Document_ID AND r.Date = z.Date; </code></pre> <p><strong><a href="http://sqlfiddle.com/#!6/cdde1/3" rel="nofollow">SQLFiddleDEMO</a></strong></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.
 

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