我有一个 SQL 语句,我想在这样的条件 case 语句中使用 distinct 关键字...
SELECT
case when <condition> then distinct t.myfield
else
null
end as my_field
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试运行查询,则会收到“缺少表达式”错误。
有什么建议?
提前致谢
Distinct 是针对整个 select 语句,而不是单个字段。您可以执行以下操作:
SELECT DISTINCT Case when <condition> then t.myfield else null end as my_field
Run Code Online (Sandbox Code Playgroud)
不过,这会影响 select 语句中的其他字段。另一种方法是将其添加到单独的查询中:
SELECT case when <condition> then t.myfield else null end as my_field
from (select distinct myfield from t) as t
Run Code Online (Sandbox Code Playgroud)