Tim Mitchell
Tim Mitchell

Reputation: 653

Is there a way to use the distinct keyword inside a conditional case statement of an SQL query?

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

Answers (1)

Dan
Dan

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

Related Questions