Referring to the sections in bold, basically having product codes and adding the eligible age for the product in the case statement. So below we have products where age is either 18 or 14 to use product. Created a new column as 'Eligibility'
Now referring to the second bold section, i only want accounts where the 'Eligibility'>'AgeAtOpenDate ie the account holder is too young for the account.
SELECT
CASE
WHEN EOMONTH(OpenDate,0) = a.[EtlFileDate] THEN 'New Account'
ELSE 'Existing Account'
END AS 'NewAccountsInMonth'
,CASE
**WHEN a.[ProductCode] in (801,802) THEN '18'
WHEN a.[ProductCode] in (480,481,489,490) THEN '14'
END as 'Eligibility'**
,a.[EtlFileDate]
,a.[AccountNumber]
,a.[OpenDate]
,a.[ProductCode]
,a.[ProductName]
,a.[PrimaryCAN]
,b.[Cust_Age]
,b.[Cust_BirthDate]
,**(DATEDIFF(year,b.[Cust_BirthDate],a.[OpenDate] ) as 'AgeAtOpenDate'**
FROM Histaccounts a
join Marketable b
on a.[PrimaryCAN]=b.[CAN]
**where 'Eligibility'>'AgeAtOpenDate'**
and a.[EtlFileDate] between '2021-10-31' and '2023-03-23'
and a.[ProductCode] in (480,481,489,490,802,801)
When I run the above script im still getting all the results rather than the ones that are under age.
What am I doing wrong? Does it have to do with the fact that you cant use a WHERE condition that is based on a CASE in the SELECT area?
4条答案
按热度按时间fdbelqdn1#
The issue is that you cannot use an alias in the WHERE clause that is defined in the SELECT statement. The WHERE clause is evaluated before the SELECT statement, so the alias
Eligibility
andAgeAtOpenDate
are not recognized in the WHERE clause.You can rewrite your query like that:
l5tcr1uw2#
Can you try to replace in where clause with the whole logic
r7xajy2e3#
You can insert records in temp table and then apply filter
CTE
zlhcx6iw4#
There are several issues here, but the biggest is the values
'Eligibility'
and'AgeAtOpenDate'
in theWHERE
clause are interpreted as string literals, rather than references to the column aliases, and sinceE
is greater thanA
the condition always succeeds.You can fix this in several ways, but in this instance you're probably best off repeating the
CASE
expressions. Do it exactly, and SQL Server is smart enough to know the expressions in theSELECT
andWHERE
clauses are the same and will only compute them once. Any kind of nesting or layering, and there's a chance you lose the use of indexes that might help the query.