我有这张桌子
ID | shares | value | percentage | total|
---------------------
1 2 60 0.222 270
2 4 120 0.444 270
3 3 90 0.333 270
我想输入id并分享剩余列应该自动计算在哪里
值为shares*30
百分比是总分值(值/总数)
和total是所有列值的总和
我尝试计算列,但它在总列
中不起作用我该怎么做?
答案 0 :(得分:0)
您可以将某些列声明为Computed列但是Total
列不同,我们需要创建一些Trigger来更新该列:
create table mytable(
ID int primary key,
Shares int,
Value as Shares * 30,
Percentage as cast(cast(Shares * 30 as decimal)*100/Total as decimal(4,2)),
Total int)
go
--create the trigger to update the Total column when any change is made on Shares
create trigger mytrigger on mytable
for update, insert
as
if update(Shares)
update mytable
set Total = (select sum(Value) from mytable)
插入一些数据进行测试:
insert into mytable(ID,Shares) values(1,2)
insert into mytable(ID,Shares) values(2,4)
insert into mytable(ID,Shares) values(3,3)