有没有更好的方法来创建此案例查询

时间:2011-09-08 16:44:11

标签: sql sql-server sql-server-2008

我正在创建一个可以正常工作的案例子查询,但是我确信必须有一种更简单的方法吗?

查询的目的是当billgrp_desc像'30%'时,然后从tbm.billgrp表中显示billgrp_desc。

当billgrp_desc不喜欢'30%'时,显示来自hbm.matter表的matter_code

查询如下:

select 
 case
    when bllgrp_desc like '30%' then 'billgrp_desc'
 end
from tbm.billgrp
union 
select 
 case
    when exists (select billgrp_desc
                 from tbm.billgrp
                 where billgrp_desc not like '30%') then 'matter_code'
  end
from hbm.matter

2 个答案:

答案 0 :(得分:2)

我可能会走这条路:

select 
 case
    when bllgrp_desc like '30%' then 'billgrp_desc'
    else 'matter_code'
 end
from tbm.billgrp

由于您没有从matter表中选择任何内容,因此我没有理由查询它...我也没有理由联合起来。只需在第一次选择所需的所有行。

答案 1 :(得分:1)

试试这个,我假设Matter_code是问题表中的一个字段

select 
    case
        when bllgrp_desc like '30%' then billgrp_desc
     end
from tbm.billgrp
union 
    select 
           isNull(gp.billgrp_desc,mt.matter_code)
    from hbm.matter mt
    left join billgrp gp on billgrp_desc not like '30%'
相关问题