sql server - Use result of Case statement in another Case statement -
i have quite long select
query have pasted relevant part here.
i need use result of of case
statement use in case
statement. i'm doing in sql server.
would grateful help.
select companycontact.name companyname, case when substring(headlease.tenantbreaknotice, len(headlease.tenantbreaknotice), 1) = 'm' convert(varchar(10), dateadd(dd, -365 / (12 / substring(headlease.tenantbreaknotice, 1, len(headlease.tenantbreaknotice) - 1)), headlease.tenantbreakdate), 103) when substring(headlease.tenantbreaknotice, len(headlease.tenantbreaknotice), 1) = 'y' convert(varchar(10), dateadd(dd, -365 * (substring(headlease.tenantbreaknotice, 1, len(headlease.tenantbreaknotice) - 1)), headlease.tenantbreakdate), 103) else headlease.tenantbreaknotice end [tenantbreaknotice], <-- need used in case statement below. case when [tenantbreaknotice] < convert(varchar(10), getdate(), 103) 'expiry' when [tenantbreaknotice] null 'expiry' else 'break' end [leaseeventtype] headlease
use ctes (common table expressions). in ctes can refer columns previous cte, can split case logic like.
example:
with cte_1 ( select * ,case when substring(headlease.tenantbreaknotice,len(headlease.tenantbreaknotice),1) = 'm' convert(varchar(10), dateadd(dd,-365/(12/substring(headlease.tenantbreaknotice,1,len(headlease.tenantbreaknotice)-1)),headlease.tenantbreakdate), 103) when substring(headlease.tenantbreaknotice,len(headlease.tenantbreaknotice),1) = 'y' convert(varchar(10), dateadd(dd,-365*(substring(headlease.tenantbreaknotice,1,len(headlease.tenantbreaknotice)-1)),headlease.tenantbreakdate), 103) else headlease.tenantbreaknotice end [tenantbreaknotice] ... ), cte_2 ( select * ,case when [tenantbreaknotice] < convert(varchar(10),getdate(),103) 'expiry' when [tenantbreaknotice] null 'expiry' else 'break' end [leaseeventtype] cte_1 ) select * cte_2
Comments
Post a Comment