CASE语句SQL中的多个计算

时间:2015-02-10 12:18:32

标签: sql sql-server

我正在尝试使用以下SQL代码,但是我正在努力寻找如何使用CASE语句进行多次计算,这里是代码:

SELECT 
dbo.Table1.PrimaryKeyID,
  CASE

       WHEN (number1 >0 AND number2 = 0) 
             THEN number1 = number1 + CalcView.Quantity

       WHEN (number1 =0 AND number2 <=0) 
             THEN number3 = number3 + CalcView.Quantity,
                  number2 = number2 - CalcView.Quantity

       WHEN (number1 =0 AND number2 >0) 
             THEN number3 = number3 + number2 
                  number1 = number1 + (CalcView.Quantity - number2)
                  number2 = 0
END
FROM Table1
INNER JOIN CalcViewON Table1.PrimaryKeyID= CalcView.PrimaryKeyID
WHERE Table1.PrimaryKeyID= CalcView.PrimaryKeyID
  • 该视图用于摆脱 SUM(),这将迫使我使用 GROUP BY
  • 这些名字不是我正在使用的名称,我更改了它们以便更容易理解..

正如您所看到的,我刚刚将计算结果放在那么之内,请有人指出我如何使这个声明发挥作用的正确方向吗?谢谢你能给我任何帮助

示例:

Case 1
Number1 = 5
Number2 = 0
CalcView.Quantity = 3

5 = 5 + 3 (8)


Case 2
Number 1 = 5
Number 2 = 3
Number 3 = 2
CalcView.Quantity = 3

2 = 2 + 3 (5)
3 = 3 - 3 (0)


Case 3
Number 1 = 5
Number 2 = 3
Number 3 = 2
CalcView.Quantity = 6

2 = 2 + 3 (5)
1 = 1 + (6 – 3) (4)
Number2 = 0

目标:根据3个WHEN语句更新number1,number2和number3。目前我正在使用select语句来确保我实现正确的输出......

CASE声明有哪些替代方案可以帮助我实现目标?再次感谢

1 个答案:

答案 0 :(得分:2)

您尝试使用单个number1语句计算number2number3CASE...WHEN...END,这不起作用 - 您需要3个不同的案例陈述。

如果我理解你的逻辑,那就应该这样做

SELECT 
dbo.Table1.PrimaryKeyID,
  CASE
    WHEN (number1 >0 AND number2 = 0) 
       THEN number1 + CalcView.Quantity
    WHEN  (number1 =0 AND number2 >0) 
       THEN number1 + (CalcView.Quantity - number2)
    ELSE
       number1
  END AS number1,
  CASE 
    WHEN(number1 =0 AND number2 <=0) 
       THEN number2 - CalcView.Quantity
    WHEN  (number1 =0 AND number2 >0) 
       THEN 0
    ELSE
       number2
  END AS number2,
  CASE
    WHEN (number1 =0 AND number2 <=0) 
       THEN number3 + CalcView.Quantity
    WHEN  (number1 =0 AND number2 >0) 
       THEN number3 + number2 
    ELSE
       number3
  END AS number3
FROM Table1
INNER JOIN CalcViewON Table1.PrimaryKeyID= CalcView.PrimaryKeyID
WHERE Table1.PrimaryKeyID= CalcView.PrimaryKeyID