使用百分比的SQL计算

时间:2017-05-02 18:25:19

标签: sql sql-server

我有一个表,其中包含一组订单的值,我可以对其进行基本计算,直到达到百分比。现在我的查询如下

declare @MyNumber decimal
set @MyNumber = (select SalesTax from [OrderHeader] where OrderHeaderID = 20)

select 
    sum(o.MaterialPrice) as "MatPrice",
    sum(o.LaborPrice) as "LaborPrice",
    sum(o.MaterialCost) as "MaterialCost",
    sum(isnull(o.MaterialPrice,0)) - sum(isnull(o.MaterialCost,0)) - sum(isnull(o.LaborPrice,0)) * @MyNumber as "RESULT"
from [OrderDetail] o
inner join [OrderHeader] oh on oh.OrderHeaderID = o.OrderHeaderID
where o.OrderHeaderID = 20

@MyNumber持有SalesTax,这个特定的SalesTax是7.00,我不知道如何将SalesTax转换为百分比并进行如上所示的计算

3 个答案:

答案 0 :(得分:1)

乘以.01

set @MyNumber = ((select SalesTax from [OrderHeader] where OrderHeaderID = 20) * .01)

编辑:正如SQLZim所说,你还必须指定比例尺和数字。声明小数时的精度。

答案 1 :(得分:0)

在声明decimal时,您需要指定精度和比例,例如

declare @mynumber decimal(9,6);

rextester演示:http://rextester.com/YBFY72733

简化示例:

select 
    convert(decimal,.07) as NotSpecified
  , convert(decimal(9,6),.07) as Specified

返回:

+--------------+-----------+
| NotSpecified | Specified |
+--------------+-----------+
|            0 | 0,070000  |
+--------------+-----------+

我最好猜测你想要的查询:

declare @MyNumber decimal(9,6);
set @MyNumber = (select SalesTax from [OrderHeader] where OrderHeaderID = 20)

/* we want the sales tax to be a percentage (less than 1), 0.0825 */
if @MyNumber >= 1 set @MyNumber = @MyNumber *.01;

select 
    MatPrice = sum(o.MaterialPrice)
  , LaborPrice = sum(o.LaborPrice)
  , MatieralCost = sum(o.MaterialCost)
  , SubTotal = (
      sum(isnull(o.MaterialPrice,0)) 
    + sum(isnull(o.MaterialCost,0)) 
    + sum(isnull(o.LaborPrice,0))
    )
  , SalesTax = (
      sum(isnull(o.MaterialPrice,0)) 
    + sum(isnull(o.MaterialCost,0)) 
    + sum(isnull(o.LaborPrice,0))
    ) * @MyNumber
  , Total = (
      sum(isnull(o.MaterialPrice,0)) 
    + sum(isnull(o.MaterialCost,0)) 
    + sum(isnull(o.LaborPrice,0))
    ) * (@MyNumber+1)
from [OrderDetail] o
  inner join [OrderHeader] oh 
    on oh.OrderHeaderID = o.OrderHeaderID
where o.OrderHeaderID = 20

答案 2 :(得分:0)

试试这个:结果列乘以0.01

declare @MyNumber decimal
set @MyNumber = (select SalesTax from [OrderHeader] where OrderHeaderID = 20)

select 
    sum(o.MaterialPrice) as "MatPrice",
    sum(o.LaborPrice) as "LaborPrice",
    sum(o.MaterialCost) as "MaterialCost",
    sum(isnull(o.MaterialPrice,0)) - sum(isnull(o.MaterialCost,0)) - sum(isnull(o.LaborPrice,0)) * @MyNumber*0.01 as "RESULT"
from [OrderDetail] o
inner join [OrderHeader] oh on oh.OrderHeaderID = o.OrderHeaderID
where o.OrderHeaderID = 20