两个基本相同的字段比较后,联合查询~~~~~~~~~~~再线等
有两个表,其中有一字段(BH)内容基本相同
TAB1 (4千多条数据)
BH SL
6W801 10
5W6801 20
2W7011 15
3W652 11
。。。
TAB2 ( 1万多条数据 )
BH ZL
6W801-A-JB 6
5W6801-SH 5.5
2W7011-X 8
3W652-C 9
。。。
说明当TAB1和TAB2通过BH比较时,当BH的后缀遇到 –A,-JB,-SH,-C时,但前几位字符相同时,认为两字段相同.
联合查询的结果为
BH SL ZL
6W801 10 6
5W6801_ 20 5.5
3W652 11 9
…
用SQL可以实现吗?
谢谢大家:)))
[解决办法]
create table A(BH varchar(20),SL decimal(18,1))insert into A values('6W801' , 10 )insert into A values('5W6801', 20 )insert into A values('2W7011', 15 )insert into A values('3W652' , 11 )create table B(BH varchar(20),SL decimal(18,1))insert into B values('6W801-A-JB', 6 )insert into B values('5W6801-SH' , 5.5) insert into B values('2W7011-X' , 8 )insert into B values('3W652-C' , 9 )goselect a.bh , a.sl asl,b.sl as bsl from a,bwhere (a.bh = b.bh) or (a.bh = left(b.bh,charindex('-',b.bh)-1) and charindex('-',b.bh) > 0)drop table A,B/*bh asl bsl -------------------- -------------------- -------------------- 6W801 10.0 6.05W6801 20.0 5.52W7011 15.0 8.03W652 11.0 9.0(所影响的行数为 4 行)*/
[解决办法]
create table t1
(BH varchar(10) , SL int )
insert into t1
select '6W801' , 10 union all
select '5W6801', 20 union all
select '2W7011', 15 union all
select '3W652' , 11
create table t2
(BH varchar(100), ZL numeric(10,2))
insert into t2
select '6W801-A-JB', 6 union all
select '5W6801-SH' , 5.5 union all
select '2W7011-X' , 8 union all
select '3W652-C' , 9
select a.* ,b.* from
t1 a join t2 b
on a.BH=LEFT(b.BH,charindex('-',b.BH)-1)
BH SL BH ZL
---------- ----------- ---------------------------------------------------------------- ------------
6W801 10 6W801-A-JB 6.00
5W6801 20 5W6801-SH 5.50
2W7011 15 2W7011-X 8.00
3W652 11 3W652-C 9.00
(所影响的行数为 4 行)
[解决办法]
SELECT TAB1.BH,TAB1.SL,TAB2.ZL FROM TAB1 JOIN TAB2 ON CHARINDEX(TAB1.BH,TAB2.BH)>0
WHERE LTRIM(TAB2.BH,LEN(TAB1.BH)) IN ('-A','-JB','-SH','-C','-A-JB')
----
没测试过,让您见笑了