2014-10-04 77 views
2

我想要在父表上創建一個計算列,該列將包含基於父級的子行的ID。根據子值填充父字段

示例中,父表:

ID Name    CalculatedClassification 
1 Parent Item #1  (computed, should return 1) 
2 Parent Item #2  (computed, should return 2) 
3 Parent Item #3  (computed, should return -1 as there is a mixed result) 

舉例子表

ID Name    ParentRow  ClassificationID 
    1 Child Item #1  1    1 
    2 Child Item #2  1    1 
    3 Child Item #3  1    1 
    4 Child Item #4  2    2 
    5 Child Item #5  2    2 
    6 Child Item #6  3    1 
    7 Child Item #7  3    0 
    8 Child Item #8  3    1  

有一個多對多的表連接兩個,但我已經離開了這一點的簡單性。此外,ClassificationID是分類標識表的外鍵,可隨時間增長。

有關如何在函數或其他SQL服務器構造中實現此操作的任何想法?

謝謝!

回答

3

我不建議在引用其他表時創建computed column

雖然有幾種方法可以做到這一點。一種是使用minmax聚集了case語句來確定該值:

select p.id, 
     p.name, 
     case 
      when min(c.classificationid) = max(c.classificationid) 
      then max(c.classificationid) 
      else -1 
     end CalculatedClassification 
from parent p 
    join child c on p.id = c.parentrow 
group by p.id, p.name 
+0

完美,我只是測試它在我實際的數據庫和它的作品就像一個冠軍。非常感謝你!!!!!另外,我正在重新思考計算的列,並可能使用視圖來將所有內容組合在一起。 – testuser900 2014-10-04 03:05:44