Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdate with nested case for previous dates
    primarykey
    data
    text
    <p>I have a table with following columns:</p> <pre><code>Document_ID, Customer_ID, Date, LoanedMoney. </code></pre> <p>I've created a new <code>LoanedDate</code> column. I want to fill dates to <code>LoanedDate</code> in the following way: </p> <ol> <li>If the previous <code>Date</code> or previous date doesn't exists (it doesn't means always -1 day) with the same <code>Document_ID</code> and <code>Customer_ID</code> is null -> copy <code>LoanedMoney</code> value and update with that value; </li> <li>If the previous <code>Date</code> (it doesn't means always -1 day) with the same <code>Document_ID</code> and <code>Customer_ID</code> is not null -> copy it and update with that value; </li> <li>Else set <code>NULL</code> to <code>LoanedDate</code> </li> </ol> <p>My approximate logic to determine the previous Date (don't know how to put it in case statement):</p> <pre><code>SELECT TOP 1 Z1.Date FROM DBANME Z1 LEFT JOIN DBNAME Z2 ON Z1.Document_ID = Z2.Document_ID AND Z1.Customer_ID = Z2.Customer_ID AND CONVERT(CHAR(8), Z1.Date, 112) &lt; CONVERT(CHAR(8), Z2.Date, 112) ORDER BY Date DESC </code></pre> <p>I have done something like this:</p> <pre><code>DECLARE @Min datetime, @Prev datetime SELECT @Min = MIN(Date) FROM DBNAME UPDATE DBNAME SET LoanedDate CASE WHEN (LoanedMoney &gt; 0) -- SET @Prev = CASE WHEN @Prev IS NULL THEN Date ELSE @Prev ELSE NULL </code></pre> <p>What's the best way to implement it?</p> <p>What I have:</p> <pre><code>Document_ID, Customer_ID, Date, LoanedMoney, LoanedDate 1, 1, 2012-04-30, 30, NULL 1, 1, 2012-04-29, 50, NULL 1, 1, 2012-04-28, 50, NULL 1, 1, 2012-04-27, 0, NULL 1, 1, 2012-04-26, 20, NULL </code></pre> <p>What I expect:</p> <pre><code>Document_ID, Customer_ID, Date, LoanedMoney, LoanedDate 1, 1, 2012-04-30, 30, 2012-04-28 1, 1, 2012-04-29, 50, 2012-04-28 1, 1, 2012-04-28, 50, 2012-04-28 1, 1, 2012-04-27, 0, NULL -- Because LoanedMoney = 0 1, 1, 2012-04-26, 20, 2012-04-26 </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. 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