0

我有一个如下所示的查询:

SELECT  LossCost, CoverageID                
FROM BGILossCost] 
WHERE CoverageID IN (1, 2) AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL)           

并返回以下数据,这是正确的:

LossCost                                CoverageID
--------------------------------------- -----------
0.012                                   1
0.034                                   2

但我想要做的是根据 CoverageID 的值设置两个变量

这是伪代码:

SELECT  @Var1 = CASE CoverageID = 1 THEN LossCost END,
  @Var2 = CASE CoverageID = 2 THEN LossCost END             
FROM BGILossCost] 
WHERE CoverageID IN (1, 2) AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL) 

我总是可以执行以下操作,但我希望出于性能原因我不必两次加入同一张桌子

SELECT  @Var1 = LossCost                    
FROM BGILossCost] 
WHERE CoverageID = 1 AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL) 

SELECT  @Var2 = LossCost                    
FROM BGILossCost] 
WHERE CoverageID = 2 AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL) 

任何的意见都将会有帮助。

4

1 回答 1

3

你非常接近,这不起作用:

SELECT
  @Var1 = MAX(CASE WHEN CoverageID = 1 THEN LossCost END),
  @Var2 = MAX(CASE WHEN CoverageID = 2 THEN LossCost END)  
FROM BGILossCost
WHERE CoverageID IN (1, 2) AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL);
于 2012-06-28T21:12:03.553 回答