I am trying to create a query that will only add AND clauses where certain conditions are met.
This is what I need:
SELECT DISTINCT id name active FROM team WHERE id = 1234 IF team.active = 'y' AND team.id IN { query } ELSEIF team.active = 'n' AND team.id IN { query }
But I'm not sure how to do this in SQL. Any suggestions?
SELECT DISTINCT id name active FROM team WHERE id = 1234 AND (team.active = 'y' AND team.id IN { query }) OR (team.active = 'n' AND team.id IN { query })
You use the AND and OR logic to create the logic.
You can use logical logic like this
SELECT ... FROM team WHERE id = 1234 AND ( (team.active = 'y' AND team.id IN query) OR (team.active = 'n' AND team.id IN query) )
Did I miss the difference in the two branches?
You can use the decoding instruction to achieve the result.
SELECT DISTINCT id name active FROM team WHERE id = 1234 and team.id in ( decode (team.active,'y',(query),'n',(query))
you can also use case argument