SQL - 在当前条件行上运行

时间:2014-05-17 08:39:17

标签: sql

我想用免费的sql'模拟器'来说明我的问题: http://sqlzoo.net/wiki/SELECT_from_Nobel_Tutorial

假设我得到了一个主题/赢家对的列表(我将它们放在WHERE..OR子句中)并希望将它们全部列在结果中,并附加一个标记“在DB中?” Y / N

我试着准备像:

select subject, winner, 
( case 
  when winner is null then 'N'
  else 'Y'
) as "Is in DB?" 
from nobel 
where (subject='Literature' and winner='Saint-John Perse')
or (subject='Medicine' and winner='Sir Frank Macfarlane Burnet')
or (subject='Medicine' and winner='Peter Medawar')
or (subject='Medicine' and winner='Christiano Ronaldo')

只有最后一个OR条件不会返回任何结果。 尽管我还希望它与标志N一起列出,否则我不会把CASE句子放到所有现有行。

不确定CASE句子是否正确。也试过

case winner when is null then 'N'

可能是SELECT IN SELECT或临时表吗?请建议

3 个答案:

答案 0 :(得分:1)

您没有指定DBMS,因此这是ANSI SQL:

with check_data (subject, winner) as (
   values 
     ('Literature', 'Saint-John Perse'), 
     ('Medicine', 'Sir Frank Macfarlane Burnet'),
     ('Medicine', 'Peter Medawar'),
     ('Medicine', 'Christiano Ronaldo')
) 
select cd.subject, 
       cd.winner, 
       case 
       when 
         winner is null then 'N'
         else 'Y'
       end as "Is in DB?" 
from check_data cd.
  left join nobel n 
     on n.subject = cd.subject  
    and n.winner = cd.winner

并非所有DBMS都支持"匿名"但是使用values的行构造函数。因此,您可能需要在公用表表达式中进行一些虚拟选择。

答案 1 :(得分:0)

Declare @Temp Table (Subject nVarchar(50), Winner nVarchar(50))

Insert  @Temp   (Subject, Winner)
    Values  ('Literature' ,'Saint-John Perse'),
        ('Medicine' ,'Sir Frank Macfarlane Burnet'),
        ('Medicine' ,'Peter Medawar'),
        ('Medicine' ,'Christiano Ronaldo')

select  subject, winner, 
    ( case 
      when nobel.Winner is null then 'N'
      else 'Y'
    ) as [Is in DB?] 
    from nobel Left Outer Join @Temp  A
        On nobel.Subject = A.Subject And nobel.Winner = A.Winner

答案 2 :(得分:0)

从某种意义上说,你无法从中得到任何东西,你需要让域名可供选择。使用像Meysam Tolouee这样的临时表是一种方式,另一种方式是:

select x.subject, x.winner
     , case when y.subject is null then 'N' else 'Y' end as is_in_db
from ( 
    select 'Literature' as Subject
         , 'Saint-John Perse' as Winner
    union
    select 'Medicine' as Subject
         ,'Sir Frank Macfarlane Burnet' as Winner
    union
    select 'Medicine' as Subject
         ,'Peter Medawar' as winner
    union
    select 'Medicine' as subject
         ,'Christiano Ronaldo' as winner
) as x
left join nobel y
    on x.subject = y.subject
   and x.winner = y.winner

Literature  Saint-John Perse    Y
Medicine    Sir Frank Macfarlane Burnet Y
Medicine    Peter Medawar   Y
Medicine    Christiano Ronaldo  N