使用CASE WHEN动态设置SQL查询的结果

时间:2010-05-27 12:58:36

标签: sql sql-server-2005 tsql

SELECT  MyTable.Name,
        (
          SELECT CASE WHEN ISNULL(SUM(TotalDays), 0) <= 0 THEN 0 
                      ELSE SUM(TotalDays) 
          END AS Total
          FROM    Application AS Applications
          WHERE   (ID = MyTable.id)
        ) - MIN(Assignments) AS Excesses
FROM    MyTable

上面的TSQL语句是主查询中的子查询。当我运行它时,如果TotalDays为NULL或&lt; = 0,则Total设置为0(零)。

我想在这里做的是将整个查询(Excesses)的结果设置为0.我想要(Excesses)这是 Total - Min(赋值)的结果)如果为NULL或&lt; = 0。

,则设置为0

我希望CASE WHEN适用于整个查询,但我正在努力使其正确。

2 个答案:

答案 0 :(得分:1)

SELECT
  MyTable.Name,
  CASE WHEN
    0 < (SELECT SUM(TotalDays) FROM Application WHERE ID = MyTable.id) - MIN(Assignments)
  THEN
    (SELECT SUM(TotalDays) FROM Application WHERE ID = MyTable.id) - MIN(Assignments)
  ELSE
    0
  END AS [Excesses]
FROM
  MyTable

注意:MS SQL Server不会独立执行这两个相关子查询,它实际上会识别它们是相同的并重新使用结果。

替代:

SELECT
  MyTable.Name,
  CASE WHEN
    0 < SUM([application].TotalDays) - MIN([MyTable].Assignments)
  THEN
    SUM([application].TotalDays) - MIN([MyTable].Assignments)
  ELSE
    0 -- If either aggregate is NULL, 0 will still be returned
  END AS [Excesses]
FROM
  MyTable
LEFT JOIN
  Application
    ON [application].ID = [MyTable].id

答案 1 :(得分:0)

SELECT  MyTable.Name, CASE WHEN ISNULL(SUM(TotalDays), 0) <= 0 THEN 0 ELSE SUM(TotalDays) END AS Total
FROM    Application AS Applications
JOIN    MyTable
ON      Applications.id = mytable.id
GROUP BY
        MyTable.id, MyTable.name
HAVING  CASE WHEN ISNULL(SUM(TotalDays), 0) <= 0 THEN 0 ELSE SUM(TotalDays) END > 0