SQL:带有“存在”的case-when语句

时间:2010-07-28 14:40:15

标签: sql teradata

我希望能够设置添加一个回答问题的字段“对于此记录中的值,该值是否满足另一个表中的某些条件?”。我以为我会尝试使用case-when exists,但Teradata(我的dbms)不喜欢它。有什么建议吗?

select foo,
   (case when exists (select x.foo
                      from somedb x
                      where x.bar > 0)
    then '1' else '0' end) as MyFlag

from mydb

5 个答案:

答案 0 :(得分:11)

您似乎错过了END声明的CASE

select foo,
   (case when exists (select x.foo
                      from somedb x
                      where x.bar > 0)
    then '1' else '0' END) as MyFlag

from mydb

答案 1 :(得分:3)

这可能有多种解决方案。有时两个表之间存在关系。然后我创建一个JOIN并在WHERE子句中处理它。我不知道Teradata,但在Oracle中,我也可以这样做。

SELECT foo 
FROM   mydb
WHERE  (select count(*) from somedb where x.bar > 0) > 0

或者更像是你的代码

select foo,  
   (case when (select count(*)
                      from somedb x  
                      where x.bar > 0) > 0   
    then '1' else '0') as MyFlag       
from mydb

我知道只在WHERE子句中使用EXISTS“我只想要下面的SELECT给我一些东西的行”。只有在一个表和另一个表之间存在某种连接时才有意义。

select id,foo from mydb y
where exists (select x.id from somedb x where x.id = y.id)

答案 2 :(得分:2)

我无法想出一个易于阅读的解决方案(当你像我一样笨拙的时候关键),所以我做了一个临时表的联盟:

create multiset table someDb.NiceFlags as
(
    select t.foo,
           '1' as myFlag
    from someDb.pos_txn_mstr t
    where exists(select x...)

  union all

    select t.foo,
           '0' as myFlag
    from someDb.pos_txn_mstr t
    where not exists(select x...)

) with data primary index(foo)

但现在我不觉得自己像个硬汉:(

答案 3 :(得分:0)

由于您只对1和0感兴趣的标志值,请尝试以下方法:

select foo,
   coalesce((select max(1)
             from somedb x
             where x.bar > 0), 0) as MyFlag
from mydb

答案 4 :(得分:0)

不要在案例中使用from子句

Case when exists(select x.foo where blahblah>0 then 1 end) from mydb
Left /inner join somedb x
相关问题