根据子值填充父字段

时间:2014-10-04 02:42:34

标签: sql sql-server

我想在父表上创建一个计算列,该列将包含基于父表的子行的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是分类ID表的外键,可以随着时间的推移而增长。

关于如何在函数或其他SQL Server构造中执行此操作的任何想法?

谢谢!

1 个答案:

答案 0 :(得分: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
相关问题