SQL - 减去2列中的值 - 添加到新列

时间:2016-02-29 13:04:34

标签: sql

*编辑*

现在感谢原始代码正常工作,感谢一些优秀用户的帮助!

 SELECT 
               STOCK.STOCK_CODE As Stock_Code,
               STOCK.SHORT_DESC As Stock_Description,
               STOCK.AVAILABILITY As Available, 
               SUM(SORDER_ITEM.QTY_SOLD) As Quantity_Sold,
               ABS(CAST(STOCK.AVAILABILITY AS INT) - CAST(SORDER_ITEM.QTY_SOLD AS INT)) AS ACTUAL
FROM 
    STOCK INNER JOIN SORDER_ITEM ON STOCK.STOCK_ID=SORDER_ITEM.STOCK_ID
GROUP BY SORDER_ITEM.QTY_SOLD, STOCK.STOCK_CODE, STOCK.SHORT_DESC, STOCK.AVAILABILITY

我已经完成了GROUP BY,但数据仍然是这样的:

5000A   TShirt  107 28  93
5000A   TShirt  107 21  86
5000A   TShirt  107 14  100

但是它应该是:

5000A TShirt - 107 63 44

样本数据* SQL RETURNS:

5000A   Tshirt  107 28  93
5000A   Tshirt  107 21  86
5000A   Tshirt  107 14  100

STOCK

5000A - TSHIRT - 107

SORDER_ITEM

5000A - TSHIRT - 28
5000A - TSHIRT - 21
5000A - TSHIRT - 14

2 个答案:

答案 0 :(得分:0)

当你写:

STOCK.AVAILABILITY - SORDER_ITEM.QTY_SOLD

其中一个不是数字类型。您需要先将其转换为数字类型,然后才能在算术抑制中使用它。 请在此处查看转换逻辑:https://msdn.microsoft.com/en-us/library/ms187928.aspx?f=255&MSPPError=-2147217396

答案 1 :(得分:0)

正如错误明确指出的那样,您要减去的一个字段是varchar。尝试将其转换为整数

 SELECT 
               STOCK.STOCK_CODE As Stock_Code,
               STOCK.SHORT_DESC As Stock_Description,
               STOCK.AVAILABILITY As Available, 
               SORDER_ITEM.QTY_SOLD As Quantity_Sold,
               ABS(CAST(STOCK.AVAILABILITY AS INT) - CAST(SORDER_ITEM.QTY_SOLD AS INT)) AS ACTUAL
FROM 
    STOCK INNER JOIN SORDER_ITEM ON STOCK.STOCK_ID=SORDER_ITEM.STOCK_ID

如果它仍然无法解决您的问题,您的字段中可能会有错误数据,即某些字母或特殊字符。尝试按降序排序并检查字段中是否所有数字都是正确的。

编辑 - 也可以使用“可用性”字段的总和

SELECT 
               STOCK.STOCK_CODE As Stock_Code,
               STOCK.SHORT_DESC As Stock_Description,
               SUM(STOCK.AVAILABILITY) As Available, 
               SUM(SORDER_ITEM.QTY_SOLD) As Quantity_Sold,
               ABS(CAST(SUM(STOCK.AVAILABILITY) AS INT) - CAST(SUM(SORDER_ITEM.QTY_SOLD) AS INT)) AS ACTUAL
FROM 
    STOCK INNER JOIN SORDER_ITEM ON STOCK.STOCK_ID=SORDER_ITEM.STOCK_ID
GROUP BY STOCK.STOCK_CODE, STOCK.SHORT_DESC