Reputation: 121
I am trying to use the output of a CASE WHEN for a different column calculation, but I do not quite know how to.
Example:
CASE
WHEN (T.Delivery_Option = 'International Standard') AND (T.[Net_Qty] * T.[Unit_Charge]) < 50 THEN 4.99
WHEN (T.Delivery_Option = 'International Standard') AND (T.[Net_Qty] * T.[Unit_Charge]) >= 50 THEN 0
ELSE 0
END AS 'Test',
What would I need to do, to use the output of "Test" in a different calculation such as:
T.[Net_Qty] / test
Upvotes: 1
Views: 196
Reputation: 1269623
SQL Server supports lateral joins. This is a nifty feature that allows you to define new columns in the FROM
clause . . . and they can then be used throughout the query:
SELECT . . .,
v.test,
t.Net_Qty / NULLIF(v.Test, 0)
FROM T CROSS APPLY
(VALUES (CASE WHEN T.Delivery_Option = 'International Standard' AND T.[Net_Qty] * T.[Unit_Charge] < 50 THEN 4.99
WHEN T.Delivery_Option = 'International Standard' AND T.[Net_Qty] * T.[Unit_Charge] >= 50 THEN 0
ELSE 0
END)
) v(Test)
Also note the use of NULLIF()
. Test
can easily take on 0
values, so you need to take that into account. In fact, the second WHEN
is not needed because it returns the same value as the ELSE
, so this can be simplified to:
FROM T CROSS APPLY
(VALUES (CASE WHEN T.Delivery_Option = 'International Standard' AND T.[Net_Qty] * T.[Unit_Charge] < 50 THEN 4.99
ELSE 0
END)
) v(Test)
Upvotes: 2
Reputation: 84
You can use subquery like this
SELECT R.Test*5 FROM (
SELECT CASE
WHEN (T.Delivery_Option = 'International Standard') AND (T.[Net_Qty] * T.[Unit_Charge]) < 50 THEN 4.99
WHEN (T.Delivery_Option = 'International Standard') AND (T.[Net_Qty] * T.[Unit_Charge]) >= 50 THEN 0
ELSE 0
END AS 'Test'
FROM TBL T
) as R
Upvotes: 2
Reputation: 521063
One option is to put your current logic into a CTE and then subquery it:
WITH cte AS (
SELECT *,
CASE WHEN Delivery_Option = 'International Standard' AND [Net_Qty] * T.[Unit_Charge] < 50 THEN 4.99
WHEN Delivery_Option = 'International Standard' AND [Net_Qty] * T.[Unit_Charge] >= 50 THEN 0
ELSE 0 END AS test
FROM yourTable
)
SELECT [Net_Qty] / test AS item
FROM cte;
Upvotes: 2
Reputation: 311163
The easiest way to reuse it would probably be to use a common table expression (CTE):
WITH cte AS (
SELECT *,
CASE
WHEN (T.Delivery_Option = 'International Standard') AND (T.[Net_Qty] * T.[Unit_Charge]) < 50 THEN 4.99
WHEN (T.Delivery_Option = 'International Standard') AND (T.[Net_Qty] * T.[Unit_Charge]) >= 50 THEN 0
ELSE 0
END AS Test
FROM T
)
SELECT Net_Qty / Test
Upvotes: 2