在select语句中有条件地选择变量

时间:2016-04-15 17:15:38

标签: sql-server case

我试图弄清楚我是否应该使用案例,子查询或其他内容进行以下操作。

在select语句中,我想根据@Z的值选择变量X或变量Y.

如果@Z为NULL,请从#table中选择@X。

如果@Z IS NOT NULL,请从#table中选择@Y。

示例代码,我认为可以使用,但我不认为我做对了。

具体代码:

    case when @GroupCode is NULL
    THEN TP.ProductID ELSE NULL END,
    case when @GroupCode is not NULL
    THEN TP.GroupCode ELSE NULL END,

完整代码

 SELECT
        T.TreatmentID,
        T.SamplingRandomNumber, 
        T.Stage,
        TreatmentOrdinal,
        case when @GroupCode is NULL
        THEN TP.ProductID ELSE NULL END,
        case when @GroupCode is not NULL
        THEN TP.GroupCode ELSE NULL END,
        CASE WHEN E.GroupPricing = 1 THEN TP.GroupCode ELSE 0 END AS OptimizationGroupID,
        @moneyZero AS Revenue,
        TP.CalculatedFrom,
        EG.Description,
        E.GroupPricing,
        TP.CurrencyCode
        ,
        TIP.*
    INTO #TreatmentDetails
    FROM AnalyticsDW.Treatment T
        INNER JOIN AnalyticsDW.TreatmentProduct TP ON T.TreatmentID = TP.TreatmentID 
        INNER JOIN AnalyticsDW.Product           P ON TP.ProductID  = P.ProductID
        LEFT JOIN  #t TIP on TIP.TreatmentID2=T.TreatmentID
        LEFT JOIN AnalyticsDW.ExperimentGroup   EG ON TP.GroupCode  = EG.ExperimentGroupCode
        LEFT JOIN AnalyticsDW.Experiment         E ON TP.GroupCode  = E.ExperimentGroupCode
             AND P.ProviderCode         = E.ProviderCode
             AND P.ProductCode          = E.ProductCode
             AND P.ClientCode           = E.ClientCode
             AND P.ProductVariationCode = E.ProductVariationCode
    WHERE 
    T.LoggedUTC BETWEEN @fromDate AND @toDate
    AND 
      T.Stage IN (0,1)
    AND 
     --TP.TreatmentID=13
    TP.TreatmentID BETWEEN @MinTreatmentID AND @MaxTreatmentID
    AND   P.ClientCode       = @ClientCode
    AND   (@provider         IS NULL OR P.ProviderCode          = @provider)
    AND   (@product          IS NULL OR P.ProductCode           = @product)
    AND   (@productVariation IS NULL OR P.ProductVariationCode  = @productVariation)
    AND   (@GroupCode        IS NULL OR TP.GroupCode            = @GroupCode)

1 个答案:

答案 0 :(得分:1)

你非常接近!

case when @GroupCode is NULL
    THEN TP.ProductID
    ELSE TP.GroupCode
END AS SomeFieldname