2014-10-04 75 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