表\n
:
Rate
表Fees | Region | Rate
-----+---------+---------
A1 | Intra | 0.00015
A2 | Intra | 0.000325
A3 | Inter | 0.000025
A4 | Inter | 0.015
:
Amount
任何帮助都可以,我正在努力编写将使用表1中的不同费率更新表的案例陈述。
我试过了:
Region | Amount | A1 | A2 | A3 | A4
-------+--------+----+----+----+----
Intra | $10 | ? | ? | ? | ?
Intra | $11 | ? | ? | ? | ?
Inter | $12 | ? | ? | ? | ?
Inter | $13 | ? | ? | ? | ?
我希望应用的费率为费率A1,区域为inter / Intra,具体取决于Amount表中的Region
Update a
set A.A1 = Amount * R.Rate
from dbo.Amount as A
inner join dbo.Rate R where R.Region = A.region
我想要应用的费率是费率A2和地区是inter / Intra,具体取决于Amount表中的Region) 等
请帮忙
答案 0 :(得分:1)
这是一种方法
Update a
set
A.A1 = Amount* R1.Rate
,A.A2 = Amount* R2.Rate
,A.A3 = Amount* R3.Rate
,A.A4 = Amount* R4.Rate
from dbo.Amount as A
inner join dbo.Rate R1
on R1.Region = A.region and r1.fees = 'A1'
inner join dbo.Rate R2
on R2.Region = A.region and r2.fees = 'A2'
inner join dbo.Rate R3
on R3.Region = A.region and r3.fees = 'A3'
inner join dbo.Rate R4
on R4.Region = A.region and r4.fees = 'A4'
答案 1 :(得分:1)
我知道你的表格是如何相关的。
update Amount
set
A1 = Amount * (select Rate from Rate where Region = Amount.Region and Fees = 'A1'),
A2 = Amount * (select Rate from Rate where Region = Amount.Region and Fees = 'A2'),
A3 = Amount * (select Rate from Rate where Region = Amount.Region and Fees = 'A3'),
A4 = Amount * (select Rate from Rate where Region = Amount.Region and Fees = 'A4')
使用子查询的一个优点是,如果返回多行,则会出现错误。有理由避免使用update ... from ...
语法。根据示例数据,您似乎将拥有空值,因此如果您选择以此方式执行此操作,则需要使用outer join
而不是inner join
。