我正在尝试通过使用MS SQL表创建的列的值执行一些加法,乘法和减法来创建新列。在下面的代码中,我创建了[PremiumByCodes] col。通过计算。同样,当我尝试创建col。 [佣金],它显示了我,无效的列名“PremiumBYCodes”。我还想对Deduction列进行相同类型的乘法并创建一个新列。有关如何继续这样做的任何建议吗?
select
[PremiumByCodes] = a.[NWP]/(1-c.[Commission%]-c.[Deduction%]),
[Commission] = [PremiumByCodes] /c.[Commission%],
[Deduction] = [PremiumByCodes] /c.[Deduction%],
答案 0 :(得分:1)
这看起来像SQL Server代码。
首先,数据库不允许在定义它们的同一SELECT
中重用列别名。通常的方法是使用子查询或CTE。另一种方法使用横向连接,使用APPLY
:
select v.PremiumByCodes, v.PremiumByCodes / c.[Commission%] as Commission,
v.PremiumByCodes /c.[Deduction%] as Deduction,
. . .
from . . . outer apply
(values (a.[BHSINWP]/(1-c.[Commission%]-c.[Deduction%]) )) v(PremiumByCodes)
. . .
答案 1 :(得分:0)
在sql-server中,除了查询的order by
之外,您不能通过别名引用列。
select
[PremiumByCodes] = a.[BHSINWP]/(1-c.[Commission%]-c.[Deduction%])
, [Commission] = (a.[BHSINWP]/(1-c.[Commission%]-c.[Deduction%]))/c.[Commission%]
, [Deduction] = (a.[BHSINWP]/(1-c.[Commission%]-c.[Deduction%]))/c.[Deduction%]