2017-02-16 17 views
2

我有一個衡量學生成績表student在我的數據庫如下:如何更新在同一個表基於先前數據的SQL表

ID TestDate PerformanceStatus (PS) 
1 15/03/2016 0 
1 01/04/2016 2 
1 05/05/2016 1 
1 07/06/2016 1 
2 15/03/2016 0 
2 01/04/2016 2 
2 05/05/2016 1 
2 07/06/2016 3 
2 23/08/2016 1 

我想更新我的表有一個新列PreviousPerformanceStatus。 這PreviousPerformanceStatus是基於performanceStatus計算監測,如下: 注:如果沒有performanceStatus的TestDate記錄之前,我想使PreviousPerformanceStatus = PerformanceStatus

ID TestDate PS PreviousPerformanceStatus 
1 15/03/2016 0 0 
1 01/04/2016 2 0 
1 05/05/2016 1 2 
1 07/06/2016 1 1 
2 15/03/2016 0 0 
2 01/04/2016 2 0 
2 05/05/2016 1 2 
2 07/06/2016 3 1 
2 23/08/2016 1 3 

如何更新我的SQL表?我應該使用連接嗎? 謝謝。

+0

邏輯不清晰(或者可能你有一個錯字)。你能解釋一下規則是什麼嗎? –

+0

下面是一個提示:首先,編寫一個返回結果的查詢(一條SELECT語句)。是的,JOIN操作是實現結果的一種方式。或者,您可以使用相關的子查詢。一旦你有一個SELECT語句,你可以將它轉換成一個UPDATE語句。 – spencer7593

+0

舉一個例子,我們使用ID = 1的學生。該previousPerformanceStatus是基於PerformanceStatus從「早期的」測試日期計算,所以當TestDate = 01/04/2016年,我想從TestDate = 15/03/2016使用的數據。但是,如果我找不到任何以前的數據,我將默認PreviousPerformanceStatus與PerformanceStatus –

回答

2

假設testdateDATE數據類型(而不是VARCHAR)

並假設(id,testdate)元組是student

UNIQUE我們可以在SELECT列表中使用相關子查詢。舉個例子:

SELECT t.id 
     , t.testdate 
     , t.performancestatus 
     , (SELECT p.performancestatus 
      FROM student p 
      WHERE p.id = t.id 
      AND p.testdate < t.testdate 
      ORDER BY p.testdate DESC 
      LIMIT 1 
     ) AS previousperformancestatus 
FROM student t 
ORDER BY t.id, t.testdate 

一旦我們確認SELECT語句給了我們正在尋找的結果,我們可以將它轉換爲UPDATE語句。既可以作爲內聯視圖,也可以直接使用相關的子查詢。

UPDATE student t 
    SET t.previousperformancestatus 
     = (SELECT p.performancestatus 
      FROM student p 
      WHERE p.id = t.id 
      AND p.testdate < t.testdate 
      ORDER BY p.testdate DESC 
      LIMIT 1 
     ) 

如果testdateDATE數據類型,或者是不存儲在規範格式,然後再「小於」比較是不能保證限制行的「較早」 testdate。並且「order by」不能保證首先返回最近的「更早」的測試日期。

對於「第一」 testdate,當沒有更早testdate,子查詢將返回NULL。我們可以使用表達式爲NULL值轉換爲0。我們可以換子查詢的功能,IFNULL(<subquery> ,0)

+0

中的值謝謝 –

相關問題