![](/img/trans.png)
[英]How to use column alias of create table statement in underlying select-join statement?
[英]How to use select within constraint or column level in create table
我有这张桌子
ID | shares | value | percentage | total|
---------------------
1 2 60 0.222 270
2 4 120 0.444 270
3 3 90 0.333 270
我想输入id并分享剩余的列,应自动计算其中value为shares*30
,百分比为value除以total(值/总计),total为所有列值的总和
我尝试计算列,但在总列中不起作用
我怎样才能做到这一点?
您可以将某些列声明为“计算列”,但是“ Total
列有所不同,我们需要创建一些触发器来更新该列:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.