嵌套案例然后在SQL中

时间:2016-04-05 13:57:16

标签: sql sql-server

我正在尝试执行以下涉及复杂查询的操作; 1.首先,我尝试根据某些逻辑选择列 2.然后根据所选列的值选择一个值 3.最后根据前一个值应用逻辑来获得最终值

如何在第3个案例的ELSE中得到2的结果......然后声明?

CASE 
    CASE 
        CASE 
            WHEN MDC.Network ='I' THEN INNBenefitID ELSE OONBenefitID 
        END
        WHEN 'INNDWO' THEN CASE WHEN DWO.Description IS NOT NULL THEN DWO.Description ELSE MDC.CostShareValue END 
        WHEN 'OONDWO' THEN CASE WHEN DWO.Description IS NOT NULL THEN DWO.Description ELSE MDC.CostShareValue END 
        ELSE isnull(dbo.fn_FormatText(MDC.CostShareValue, CostShareType),'''') 
    END
    WHEN '0%' THEN 'Covered 100%'
    WHEN '$0' THEN 'Covered 100%' 
    ELSE ????
   END

2 个答案:

答案 0 :(得分:0)

你正在寻找类似的东西吗? :

declare @value varchar(255) = (
                     CASE 
                     WHEN MDC.Network ='I' THEN INNBenefitID ELSE OONBenefitID 
                     WHEN 'INNDWO' THEN CASE WHEN DWO.Description IS NOT NULL THEN DWO.Description ELSE MDC.CostShareValue
                     WHEN 'OONDWO' THEN CASE WHEN DWO.Description IS NOT NULL THEN DWO.Description ELSE MDC.CostShareValue
                     ELSE isnull(dbo.fn_FormatText(MDC.CostShareValue, CostShareType),'''') 
                     END
                   ) 

CASE 
   WHEN '0%' THEN 'Covered 100%'
   WHEN '$0' THEN 'Covered 100%' 
   ELSE @value
END

答案 1 :(得分:0)

真的,如果没有架构或样本数据,真的很难做到这一点。将来考虑为我们创建一个SqlFiddle。但是您可能考虑的一种方法是使用公用表表达式(CTE)来定义您随后查询的中间结构。

;WITH theCTE AS (SELECT 
    CASE 
        CASE 
            WHEN MDC.Network ='I' THEN INNBenefitID ELSE OONBenefitID 
        END
        WHEN 'INNDWO' THEN COALESCE(DWO.Description, MDC.CostShareValue)
        WHEN 'OONDWO' THEN COALESCE(DWO.Description, MDC.CostShareValue)
        ELSE COALESCE(dbo.fn_FormatText(MDC.CostShareValue, CostShareType), '') 
    END AS foo
FROM 
    bar
)

SELECT 
    CASE  
        WHEN foo IN ('0%', '$0') THEN 'Covered 100%'
        ELSE '' -- Do something with foo --
    END AS finalColumn
FROM 
    theCTE