Reputation: 653
I have an SQL statement in which I would like to use the distinct keyword inside a conditional case statement like so...
SELECT
case when <condition> then distinct t.myfield
else
null
end as my_field
If I try to run the query, though, I get a 'missing expression' error.
Any suggestions?
Thanks in advance
Upvotes: 2
Views: 26017
Reputation: 547
Distinct is for the entire select statement, not a single field. You could do the following:
SELECT DISTINCT Case when <condition> then t.myfield else null end as my_field
This will affect other fields in the select statement though. An alternative would be to add it to a separate query:
SELECT case when <condition> then t.myfield else null end as my_field
from (select distinct myfield from t) as t
Upvotes: 7