有没有办法在SQL查询的条件case语句中使用distinct关键字?

时间:2015-06-11 16:53:51

标签: sql sql-server

我有一个SQL语句,我想在条件case语句中使用distinct关键字,如此...

SELECT
  case when <condition> then distinct t.myfield
  else
  null
  end as my_field

但是,如果我尝试运行查询,则会出现“缺少表达式”错误。

有什么建议吗?

提前致谢

1 个答案:

答案 0 :(得分:3)

区别在于整个select语句,而不是单个字段。您可以执行以下操作:

SELECT DISTINCT Case when <condition> then t.myfield else null end as my_field

这会影响select语句中的其他字段。另一种方法是将其添加到单独的查询中:

SELECT case when <condition> then t.myfield else null end as my_field
from (select distinct myfield from t) as t