在总和内嵌套Case语句-SQL Server

时间:2019-05-10 14:22:04

标签: sql-server

对此有麻烦:

我有以下查询,可为我提供所需的确切视图。

SELECT t.Week,
       SUM(t.Hours) AS AH,
       SUM(c.Input) AS input,
       SUM(c.[recruitedPos]) AS recruitedPos,
       (SUM(t.Hours) - SUM(c.Input)) AS Possible
FROM tempPOC AS t
     LEFT JOIN (SELECT Week,
                       SUM(input) AS Input,
                       SUM([Normal Weekly Hours]) AS recruitedPos,
                       Shop
                FROM colData
                GROUP BY week,
                         Shop) AS c ON t.Week = c.Week
                                   AND c.Shop = t.Store
GROUP BY t.Week,
         t.Store
ORDER BY t.Week;

我遇到的麻烦是编写一个case语句,以将可能的别名中的任何值设置为小于0的值。

我认为这就像

一样简单
(CASE(SUM(t.Hours - c.Hours)) < 0 then 0 else Possible end as Possible)

但这给我错误

  

第156条消息,第15级,状态1,第9行
  关键字“ as”附近的语法不正确。

输入:

Week, AH, Input, RecruitedPos, Possible
1,    15, 25,    13,            -10
1,    30, 15,    15,            15

预期输出:

Week, AH, Input, RecruitedPos, Possible
1,    15, 25,    13,            0  
1,    30, 15,    15,            15

1 个答案:

答案 0 :(得分:2)

CASE
    WHEN SUM(t.Hours) - SUM(c.Input) < 0 THEN 0
    ELSE SUM(t.Hours) - SUM(c.Input)
END AS Possible