![](/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.