日期:2014-05-17  浏览次数:20392 次

求助,表A怎样与表B中的多字段匹配
现有表A,字段如下
列名:ad             ad1
列值:广河县畜牧局   null
表B,字段如下
列名:p_id   pro   c_id    city      t_id     town
列值:  1    北京   1      null        1      昌平
        3   河北    3     石家庄市     3     长安区
其中p_id、c_id与t_id是一一相对应的
怎样用表A中的ad与表B中的pro匹配成功,则在ad1输出pro,
如果匹配不成功,则与表B中的city匹配,若成功,则在ad1输出city对应的pro,
如果匹配不成功,则与表B中的town匹配,若成功,则在ad1输出与town对应的pro(存在一个town对应多个pro的情况)
匹配

------解决方案--------------------
select ad1=case when ad=pro then pro when ad=city then pro when ad=town then pro else '' end from 表A,表B
------解决方案--------------------

select N'广河县畜牧局' ad,   null as ad1
into #A
union all select N'北京畜牧局' ad,   null as ad1

select  1 p_id,N'北京' pro,1 c_id,null city,1 t_id,N'昌平' town
into #B
union all select  3 ,N'河北',3,N'石家庄市',3,N'长安区'

select ad,ad1=max(isnull(ad1,''))
from
(
select ad
,ad1=case 
when CHARINDEX(pro,ad)>0 then pro
when CHARINDEX(city,ad)>0 then city
when CHARINDEX(town,ad)>0 then town
end
from #A,#B
)t
 group by ad


这样?
------解决方案--------------------
select distinct ad,pro from 
(select ad,
ad1=case 
when CHARINDEX(pro,ad)>0 then pro
when CHARINDEX(city,ad)>0 then city
when CHARINDEX(town,ad)>0 then town
end
from #A,#B),#B where ad1=pro or ad1=city or ad1=town
这样?
------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:


select N'广河县畜牧局' ad,   null as ad1
into #A
union all select N'北京畜牧局' ad,   null as ad1

select  1 p_id,N'北京' pro,1 c_id,null city,1 t_id,N'昌平' town
into #B
union all select  3 ,N'河北',3,N'石家庄市',3,N'长安区'

select ad,ad1=max(isnull(ad1,''))
from
(
select ad
,ad1=case 
when CHARINDEX(pro,ad)>0 then pro
when CHARINDEX(city,ad)>0 then city
when CHARINDEX(town,ad)>0 then tow