select a from temp where nam='1'
union
select b from temp where nam='2'
union
select c from temp where nam='3'
union
select d from temp where nam='4'
union
select e from temp where nam='5'现在问题是如果某一条没有记录的时候就会少一行返回值,有没有什么办法当没有记录的时候能返回一个0
 

解决方案 »

  1.   


    --这样?
    --如果5这条没有记录
    select 0 where not exists(select e from temp where nam='5') 
      

  2.   


    --这样:select a from temp where nam='1' 
    union  
    select 0 where not exists(select a from temp where nam='1')
    union 
    select b from temp where nam='2' 
    union 
    select 0 where not exists(select b from temp where nam='2')
    union 
    select c from temp where nam='3' 
    union 
    select 0 where not exists(select c from temp where nam='3')
    union 
    select d from temp where nam='4'
    union 
    select 0 where not exists(select d from temp where nam='4') 
    union 
    select e from temp where nam='5'
    union 
    select 0 where not exists(select e from temp where nam='5') 
      

  3.   

    select top 5 * from
    (
    select a from temp where nam='1' 
    union 
    select b from temp where nam='2' 
    union 
    select c from temp where nam='3' 
    union 
    select d from temp where nam='4' 
    union 
    select e from temp where nam='5' 
    union 
    select 0 
    union 
    select 0 
    union 
    select 0 
    union 
    select 0 
    union 
    select 0 
    ) t
      

  4.   

    union是不行的,要union all才行
    select * from(
    select a from temp where nam='1' union select 0 a where not exists(select a from temp where name='1'))
    union all select * from(
    select b from temp where nam='2' union select 0  where not exists(select b from temp where name='2'))
    union all select * from(
    select c from temp where nam='3' union select 0 where not exists(select c from temp where name='3'))
    union all select * from(
    select d from temp where nam='4' union select 0 where not exists(select d from temp where name='4'))
    union all select * from(
    select e from temp where nam='5' union select 0 where not exists(select e from temp where name='5')) 
    另这个方法笨了点,如果信息多点应该可以简化。
      

  5.   

    DELSELECT ISNULL((SELECT d FROM temp WHERE nam='4'),0)
    union 
    SELECT ISNULL((SELECT e FROM temp WHERE nam='5'),0)