Sql Server 中的计算列

请问能不能在计算列中使用Sum()函数计算出另一个表中字段的合计

比如有以下两个表A和B, B.ParentId 的外键是A.Id,A.Num是计算列,我想在A.Num 列中写一个公式,自动得出B中所有ParentId=A.Id的Num字段的总和。 表A: Id Num 表B: Id ParentId Num

慕姐8265434
浏览 1337回答 3
3回答

达令说

计算列不能引用其他表的列,但是可以通过函数来实现,先建立下面这个函数:create function DingXue(@id int)    returns intasbegin    declare @sum int    select @sum=sum(num) from b where id=@id    return @sumend然后创建表:create table A(Id int identity(1,1), Num as dbo.DingXue(Id), tt int)create table B(Id int identity(1,1), ParentId int, Num int)测试如下:insert into A(tt) values(1)insert into B(ParentId,Num) values(1,1234)insert into B(ParentId,Num) values(1,4321)select * from Aselect * from B=================A表里的tt只是为了增加A表里的记录 :)======================其实我一直觉得数据库里没有必要存放计算列,因为“计算”这种事情,让程序来做会更简单,非要数据库来做,也可以直接使用 select a.id, sum(b.num) as num from a inner join b on a.id=b.parentid 这种方式来实现另外,也可以在B表加触发器来实现,介理相对于函数来说,我对触发器的抵触情绪更严重一些,呵呵,所以这里提供函数方式的实现

鸿蒙传说

update num =d.total  from  c inner join  (select a.aid, sum(b.num) as total from a inner join b on a.aid=b.aid group by a.aid) d on c.id = d.id

慕村9548890

建议不要这样使用,如果你非要这样用,可以试着自己写一个自定义函数
打开App,查看更多内容
随时随地看视频慕课网APP