I am relatively new in SQL coding and have a question regarding case statements.
What I want to achieve: I want to create a query being used for calculating correct obso
You don't have access to the aliases in the select clause in the same select clause. There is a simple fix and that is using a derived table or a common table expression:
;with cte as
(
Select
[Material]
,[Plnt]
,case
when [calculate 5-year demand] = 0
then 9.01
when [BAAS SO GI (601) 36] = 0
then 9.01
when [MS] <> 'BI' or [MS] <> 'BO'
then ([Stock all SP WH]/([calculate 5-year demand]/5))
when [MS] = 'BO'
then ([Stock all SP WH]/[BAAS SO GI (601) 36])
when [MS] ='BI'
then 0
else 9.01
end as [Inventory Reach]
from [BAAS_PowerBI].[dbo].[Obs]
)
select [Material]
,[Plnt]
,[Inventory Reach]
,case
when [Inventory Reach] > 9
then 1
else 0.9
end as [Devaluation Class]
from cte
The above code is using a common table expression which is (in this schenario) basically the same as using a derived table, only more readable. Here's the derived table equivalent:
select [Material]
,[Plnt]
,[Inventory Reach]
,case
when [Inventory Reach] > 9
then 1
else 0.9
end as [Devaluation Class]
from
(
Select
[Material]
,[Plnt]
,case
when [calculate 5-year demand] = 0
then 9.01
when [BAAS SO GI (601) 36] = 0
then 9.01
when [MS] <> 'BI' or [MS] <> 'BO'
then ([Stock all SP WH]/([calculate 5-year demand]/5))
when [MS] = 'BO'
then ([Stock all SP WH]/[BAAS SO GI (601) 36])
when [MS] ='BI'
then 0
else 9.01
end as [Inventory Reach]
from [BAAS_PowerBI].[dbo].[Obs]
) derived