如何根据下面的查询编写嵌套的CASE语句?

时间:2017-02-15 00:36:36

标签: sql-server tsql case

我正在使用CASE语句创建列Quoted。所以它会显示值1或0.

但是必须根据上一列DisplayStatus的条件创建列Quoted

似乎我应该在这种情况下使用嵌套的CASE语句。但我无法提出正确的查询。

SELECT 
       case when isnull(grouptt.controlno,0) <>0 AND  isnull(vwR.Premium,0) > 0 then 
      cast( 1 as bit)
      else cast( 0 as bit)
      end as Quoted,

      CASE 
           WHEN a.DisplayStatus = 'LOST' AND quoted=1  THEN 'Quoted_Lost'
           WHEN a.DisplayStatus = 'DECLINED' AND quoted=1  THEN 'Quoted_NotTakenUp'
           WHEN a.DisplayStatus = 'NOT TAKEN UP' AND quoted=1  THEN 'Quoted_Lost'
           ELSE
                  a.DisplayStatus
      END
      DisplayStatus
    FROM MyTable 

3 个答案:

答案 0 :(得分:3)

使用嵌套的CASE表达式

SELECT 
    CASE 
        WHEN ISNULL(grouptt.controlno, 0) <> 0 AND ISNULL(vwR.Premium, 0) > 0 THEN CAST(1 AS BIT)
        ELSE CAST(0 AS BIT)
    END AS Quoted,
    CASE
        WHEN ISNULL(grouptt.controlno, 0) <> 0 AND ISNULL(vwR.Premium, 0) > 0  THEN  
            CASE
                    WHEN a.DisplayStatus = 'LOST' THEN 'Quoted_Lost'
                    WHEN a.DisplayStatus = 'DECLINED' THEN 'Quoted_NotTakenUp'
                    WHEN a.DisplayStatus = 'NOT TAKEN UP' THEN 'Quoted_Lost'
                    ELSE a.DisplayStatus
            END
        ELSE a.DisplayStatus
    END AS DisplayStatus
FROM MyTable 

答案 1 :(得分:1)

您无法在同一select中重复使用该变量。解决这个问题的两种常用方法是CTE和子查询。我也喜欢第三个,outer apply

SELECT v.quoted,
       (CASE  WHEN a.DisplayStatus = 'LOST' AND v.quoted = 1 THEN 'Quoted_Lost'
              WHEN a.DisplayStatus = 'DECLINED' AND v.quoted = 1 THEN 'Quoted_NotTakenUp'
              WHEN a.DisplayStatus = 'NOT TAKEN UP' AND v.quoted = 1 THEN 'Quoted_Lost'
              ELSE  a.DisplayStatus
         END)
FROM MyTable t OUTER APPLY
     (VALUES (case when coalesce(grouptt.controlno,0) <> 0 AND  coalesce(vwR.Premium, 0) > 0 
                   then cast( 1 as bit)
                   else cast( 0 as bit)
              end)
     ) v(Quoted);

答案 2 :(得分:1)

您可以尝试使用交叉应用计算一个值的stamement。

SELECT 
   c.Quoted,

  CASE 
       WHEN a.DisplayStatus = 'LOST' AND c.quoted=1  THEN 'Quoted_Lost'
       WHEN a.DisplayStatus = 'DECLINED' AND c.quoted=1  THEN 'Quoted_NotTakenUp'
       WHEN a.DisplayStatus = 'NOT TAKEN UP' AND c.quoted=1  THEN 'Quoted_Lost'
       ELSE
              a.DisplayStatus
  END
  DisplayStatus
FROM MyTable AS a
CROSS APPLY(VALUES(
   CASE when isnull(grouptt.controlno,0) <>0 AND  isnull(vwR.Premium,0) > 0 then 
  cast( 1 as bit)
  else cast( 0 as bit)
  end)
  ) c(Quoted)