Reputation: 1106
I have a query which looks like this:
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)
And returns the following data, which is correct:
LossCost CoverageID
--------------------------------------- -----------
0.012 1
0.034 2
But what I want to do is set two variables depending in the value of CoverageID
Here is the pseudeo code:
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)
I could always do the below but I was hoping I wouldn’t have to join to the same table twice for performance reasons
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)
Any suggestions would be helpful.
Upvotes: 0
Views: 5332
Reputation: 280262
You were very close, doesn't this work:
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);
Upvotes: 3