需要将一个表的两列相乘,并从不同表的另一列中减去此结果

时间:2017-10-10 17:52:31

标签: sql-server

我有两列allocationfeerate class表,需要多列这两列和 需要将其命名为surcharge。 最后从baserate表中的Rate列中减去此值。 Class表和Rate表格为rateid作为公共字段。

我正在尝试这种方式,但收到错误:

select BASERATE - t.Surcharge from rate

(select t.Surcharge from 

(select allocationfee*RATE as SolvencySurcharge from rateclass1) as t) as m

样本日期:

rateclass1

classid   rateid    allocationfee  rate   Surcharge(calculated field=allocationfee*RATE)
101         1          20           30      60
102         2          30           50      150

现在我需要根据raterateid表中减去rateclass1的附加费。

rate  baserate      basearate-surchrge
1       200           140
2       300           150

2 个答案:

答案 0 :(得分:2)

您将从以下查询中获得所需的结果。不必要地使用子查询使查询变得复杂。

select 
r. BASERATE, 
t.allocationfee*t.RATE as surcharge,
(r.BASERATE -t.allocationfee*t.RATE) as substracted_value
from rate r 
join classtable t 
on t.rateid=r.rateid

答案 1 :(得分:0)

我同意@Rams解决方案,但我认为您需要了解编写代码时出现的问题:

select BASERATE - t.Surcharge from rate
(select t.Surcharge from 
(select allocationfee*RATE as SolvencySurcharge from rateclass1) as t) as m

您应该了解,当您从外部查询中选择字段时,该字段的名称必须与内部查询中的字段名称匹配,因此您需要将子查询更改为:

(select SolvencySurcharge  from 
    (select allocationfee*RATE as SolvencySurcharge from rateclass1) as t)

或:

 (select Surcharge from 
    (select allocationfee*RATE as Surcharge from rateclass1) as t)

我还假设你的rate值代表一个百分比,所以需要除以100:

select allocationfee*RATE/100 as Surcharge

并且您在表和外部子查询之间缺少JOIN语法:

select 
   BASERATE - Surcharge 
from 
 rate r inner join
 (select 
   Surcharge, 
   rateID 
 from 
     (select 
       rateID, 
       allocationfee*RATE/100 as Surcharge 
      from 
       rateclass1) t
     ) m on
 r.rateID = m.rateID

请注意,您还需要遍历子查询中的rateID字段,以便可以将其与rateID表中的rate字段一起使用。此外,您不需要对最外面的Surcharge字段进行限定,但如果您这样做,那么它将来自您的子查询别名m,而不是t

HTH