Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
How to write sql where condition based on column selected in case statement.

What I have tried:

I am selecting columns based on case statement and want to filter with where clause based on selected column in case statement.
Posted
Updated 23-Apr-18 20:06pm
Comments
Wendelius 19-Dec-16 18:21pm    
Can you provide an example situation
dgnr 19-Dec-16 18:41pm    
Select case when UpdatedDate is not null then UpdatedDate when InsertedDate is not null then InsertedDate else VisitedDate end
From tbl_UserTracking
where [UpdatedDate/InsertedDate/VisitedDate(based on case)] between date1 and date2

-- Where condition should be based on column selected from case statement.

If I understand the description correctly, you could use CASE in the where clause, like
SQL
...
WHERE date1 <= CASE WHEN ...
AND   date2 >= CASE WHEN ...
...
But since you just want the first non null value from different fields, I believe using COALESCE (Transact-SQL)[^] would be easier, something like
SQL
SELECT COALESCE(UpdatedDate, InsertedDate, VisitedDate)
FROM tbl_UserTracking
WHERE COALESCE(UpdatedDate, InsertedDate, VisitedDate) BETWEEN date1 AND date2
 
Share this answer
 
 
Share this answer
 
You can use IsNULL in this case.

So your query will look as below:

SQL
Select case when UpdatedDate is not null then UpdatedDate when InsertedDate is not null then InsertedDate else VisitedDate end
From tbl_UserTracking
where Isnull(UpdatedDate,Isnull(InsertedDate,VisitedDate)) between date1 and date2


Please let me know if you have any concern or query or if you are still facing issue.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900