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
A column alias is not permitted in the FROM
, WHERE
, GROUP BY
, or HAVING
clauses. You can use a subquery or CTE, but SQL Server supports lateral joins via the APPLY
keyword. This can be quite useful for introducing a column alias:
select o.Material, o.Plnt, v.[Inventory Reach],
(case when v.[Inventory Reach] > 9
then 1
else 0.9
end) as [Devaluation Class]
from [BAAS_PowerBI].[dbo].[Obs] o cross apply
(values (case when o.[calculate 5-year demand] = 0
then 9.01
when o.[BAAS SO GI (601) 36] = 0
then 9.01
when o.[MS] in ('BI', 'BO')
then (o.[Stock all SP WH] / (o.[calculate 5-year demand] / 5))
when o.[MS] = 'BO'
then (o.[Stock all SP WH] / o.[BAAS SO GI (601) 36])
when o.[MS] ='BI'
then 0
else 9.01
end
)
) values([Inventory Reach])