SQL中的减法运算符中的数据类型不兼容

时间:2017-08-03 20:50:20

标签: sql-server-2008

尝试获得average_cost_2017average_cost_2016美元差异,但收到此错误:

  

数据类型varchar和varchar在减法运算符中不兼容。

我不知道如何减去这两列。我正在使用SQL Server 2008.

以下是我正在使用的代码

SELECT DISTINCT 
    od.productcode as Product_SKU,
    o1.Quantity AS 'JULY 2017 Quantity',
    o1.Average_Price AS  'JULY 2017 Average_price',
    o1.Average_Cost AS  'JULY 2017 Average_cost',
    o2.Quantity AS 'JULY 2016 Quantity',
    o2.Average_Price AS  'JULY 2016 Average_price',
    o2.Average_Cost AS  'JULY 2016 Average_cost',
    '$' + CAST((o1.Average_Cost-o2.Average_Cost ) AS VARCHAR(20)) AS DIFF_COST
FROM
    OrderDetails od
JOIN 
    Orders o ON od.OrderID = o.OrderID 
JOIN
    (SELECT 
         productcode,
         SUM(od.Quantity) as Quantity,
         '$' + CAST((SUM((od.ProductPrice) * (od.Quantity)) / SUM(od.Quantity))AS VARCHAR(20)) AS Average_Price,
         '$' + CAST(( SUM(od.Vendor_Price) / COUNT(od.Quantity))AS VARCHAR(20)) AS Average_Cost
     FROM
         OrderDetails od
     JOIN
         Orders o ON od.OrderID = o.OrderID 
     JOIN 
         Customers c ON c.CustomerID = o.CustomerID
     WHERE
         o.OrderStatus <> 'Cancelled'
         AND o.OrderDate BETWEEN '07/01/17 00:00' AND '07/31/17 23:59'
         AND od.ProductPrice <> 0
         AND od.Quantity NOT LIKE 0
         AND c.CustomerID NOT IN ('10042', '429173') 
     GROUP BY
         productcode) AS o1 ON o1.ProductCode = od.ProductCode
JOIN
    (SELECT 
         productcode,
         SUM(od.Quantity) as Quantity,
         '$' + CAST((SUM((od.ProductPrice) * (od.Quantity)) / SUM(od.Quantity))AS VARCHAR(20)) AS Average_Price,
         '$' + CAST(( SUM(od.Vendor_Price) / COUNT(od.Quantity))AS VARCHAR(20)) AS Average_Cost
     FROM
         OrderDetails od
     JOIN
         Orders o ON od.OrderID = o.OrderID 
     JOIN 
         Customers c ON c.CustomerID = o.CustomerID
     WHERE 
         o.OrderStatus <> 'Cancelled'
         AND o.OrderDate BETWEEN '07/01/16 00:00' AND '07/31/16 23:59'
         AND od.ProductPrice <> 0
         AND od.Quantity NOT LIKE 0
         AND c.CustomerID NOT IN ('10042', '429173') 
     GROUP BY
         productcode) AS o2 ON o2.ProductCode = od.ProductCode 

0 个答案:

没有答案