表spzs如下:
id  sortid   lanmu
1     83     技术
2     98     产品
3     60     运输
4     30
5     30 
6     20
7     20
8     60    运输     
表class_1如下:
sortid      sort
20         花岗岩
30         花草
60         社会
83         分数
98         电脑
(表class_内容不会重复,但表spzs中的sortid,lanmu值有许多重复值)SELECT 
distinct h.sortid,
p.sort,
h.lanmu
from spzs h 
Left Join
(Select A.* from class_1 A Inner Join (Select sortid from class_1 Group By sortid) B On A.sortid=B.sortid) p On h.sortid=p.sortid 
本查询输出了这样的结果:         花岗岩
         花草
         社会
         分数
         电脑
         技术
         产品
         运输
         运输
可我需要的是:在表spzs中的lanmu值不为空时代替表class_1中的值,并且在表spzs中lanmu为空时,仍然使用class_1表中的sort值!十万火急!!!  

解决方案 »

  1.   

    create table spzs(id int, sortid int, lanmu varchar(10))
    insert spzs select 1,     83,     '技术'
    union all select 2,     98,     '产品'
    union all select 3,     60,     '运输'
    union all select 4,     30,  null
    union all select 5,     30,    null 
    union all select 6,     20,  null
    union all select 7,     20,  null
    union all select 8,     60,     '运输'create table class_1(sortid int, sort varchar(10))
    insert class_1 select 20,         '花岗岩'
    union all select 30,         '花草'
    union all select 60,         '社会'
    union all select 83,         '分数'
    union all select 98,         '电脑'select distinct spzs.sortid,lanmu=isnull(spzs.lanmu, class_1.sort)
    from spzs
    inner join class_1 on spzs.sortid=class_1.sortid--result
    sortid      lanmu      
    ----------- ---------- 
    20          花岗岩
    30          花草
    60          运输
    83          技术
    98          产品(5 row(s) affected)
      

  2.   

    --try to
    SELECT distinct IsNULL(h.sortid,a.SortID) as SortID,
                    isNULL(h.lanmu,a.sort) as Sort 
    from spzs as h  full Join class_1 as a
         on a.sortid=h.sortid