SQL计算负数为0

时间:2019-05-15 19:29:28

标签: sql

我有一个正在处理的库存数量查询,但是我遇到CASE问题,无法将任何负数变为0

我是根据计算得出数量的,所以我假设我也必须使用某种类型的CASE

我有几个带有负片的项目,但是我不知道如何在这个项目上CASEMAX

非常感谢您的帮助。

以下是查询示例:

SELECT 
Item AS 'Item No.',
(
 (SELECT CASE WHEN t0.OnHand > 0 THEN t0.OnHand ELSE 0 END 
  FROM TABLE 
  WHERE ItemCode = T0.[ItemCode] AND WhsCode like 'wh') +

 (SELECT CASE WHEN OnHand > 0 THEN OnHand ELSE 0 END 
  FROM TABLEX 
  WHERE ItemCode = T0.[ItemCode] AND WhsCode like 'INT') +

 (SELECT CASE WHEN OnOrder > 0 THEN OnOrder ELSE 0 END 
  FROM TABLEX 
  WHERE ItemCode = T0.[ItemCode] AND WhsCode like 'WH') +

 (SELECT CASE WHEN OnOrder > 0 THEN OnOrder ELSE 0 END 
  FROM TABLEX 
  WHERE ItemCode = T0.[ItemCode] AND WhsCode like 'INT') -

 (SELECT CASE WHEN IsCommited > 0 THEN IsCommited ELSE 0 END 
  FROM TABLEX 
  WHERE ItemCode = T0.[ItemCode] AND WhsCode like 'WH')
) AS 'Available Qty'

FROM  DBTABLE T0

1 个答案:

答案 0 :(得分:0)

CASE语句应用作单独的列。换句话说,您不需要重复单词SELECT

您应遵循此格式...

SELECT  Item AS 'Item No.', 
CASE WHEN OnOrder > 0 THEN OnOrder ELSE 0 END AS 'xyz', 
CASE WHEN IsCommited > 0 THEN IsCommited ELSE 0 END AS 'zyx'
FROM TableX

或者,如果您需要使用多个SELECT语句(例如,如果您需要从多个表中选择数据),则应该JOIN或使用CTE