Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update Query

Tags:

sql-server

I am not bad with SQL but I am having a hard time figuring this one out.

I have a table called test, with a character column called key and two datetime columns called TestTime and LastTestTime.

I am trying to write a query that will update all the rows and set the value of LastTestTime to the most recent previous TestTime for that same key.

Here is an example of how I want this to turn out:

key   testTime   lastTestTime
------------------------------
aaa   1/1/2012   null
aaa   1/2/2012   1/1/2012
aaa   1/3/2012   1/2/2012
like image 294
Dan B Avatar asked Jul 01 '26 22:07

Dan B


2 Answers

None of these answered the question. The questioner wants the most recent test time before each test, not the overall most recent:

UPDATE test 
    SET lastTestTime = (SELECT TOP(1) testTime
                        FROM test tt
                        WHERE test.key = tt.key AND tt.TestTime < test.TestTime
                        ORDER BY testTime DESC
                       )              
like image 147
Gordon Linoff Avatar answered Jul 03 '26 14:07

Gordon Linoff


UPDATE t
SET LastTestTime = t2.TestTime
FROM
    Test t JOIN 
    Test t2 
        ON t2.[Key] = t.[Key]
        AND t2.TestTime = (
            SELECT MAX(t3.TestTime)
            FROM Test t3
            WHERE 
                t3.TestTime < t.TestTime
                AND t3.[Key] = t.[Key]
        )
like image 22
Michael Fredrickson Avatar answered Jul 03 '26 15:07

Michael Fredrickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!