带有case的sql server子查询

时间:2012-03-16 15:28:11

标签: sql sql-server

我有以下sql:

    select * from 
    ( 
         select p.ID, 
         Received = (select Rec from Exp   
                     where EstAmt = (select MAX(ex.EstAmt) from Exp ex 
                                     where ex.Prot = p.ID and EstAmt > 0) 
                    )    

   From Prot  
   ) subsel 
   where Received = 1 

我想在收到的情况下做一个案例,如果它是1,那么让它说“是”,否则说“不”。 我知道如何做一个案例,但不是在这种情况下因为我收到的是一个子查询。

我尝试了以下但没有工作

     select * from 
     ( 
       select p.ID, 

       case Received = (select Rec from Exp   
                        where EstAmt = (select MAX(ex.EstAmt) from Exp ex 
                                        where ex.Prot = p.ID and EstAmt > 0) 
                  )    
      when 1 then 'Yes'
      else 'No'
      end Received
      From Prot  
     ) subsel 
    where Received = 1 

3 个答案:

答案 0 :(得分:1)

而不是

case Received = (select Rec from Exp   
                        where EstAmt = (select MAX(ex.EstAmt) from Exp ex 
                                        where ex.Prot = p.ID and EstAmt > 0) 
                  )  

尝试:

case (select Rec from Exp   
                            where EstAmt = (select MAX(ex.EstAmt) from Exp ex 
                                            where ex.Prot = p.ID and EstAmt > 0) 
                      )  

其他答案也有重要意义,但您不能将子查询的值分配给Received,只需在“case”之后使用单个值,并确保子查询不返回多个值。

答案 1 :(得分:0)

我认为您需要在'结束'之后删除'已收到'。 IE浏览器。改变:

when 1 then 'Yes'
else 'No'
end Received

when 1 then 'Yes'
else 'No'
end

答案 2 :(得分:0)

就像在过滤器中一样,在子查询之外获取此case

    select subsel.ID,
    case subsel.Received 
      when 1 then 'Yes'
      else 'No'
    end Received 
    from 
    ( 
         select p.ID, 
         Received = (select Rec from Exp   
                     where EstAmt = (select MAX(ex.EstAmt) from Exp ex 
                                     where ex.Prot = p.ID and EstAmt > 0) 
                    )    

   From Prot  
   ) subsel 
   where Received = 1