select A.PTT_PdtypeName,sum(B.ST_Number) AS SUM
FROM Table1 A
JOIN Table2 B ON A.PTT_PdtypeName = substring(B.ST_Style ,1,Len(A.PTT_PdtypeName))
GROUP BY A.PTT_PdtypeName
FROM Table1 A
JOIN Table2 B ON A.PTT_PdtypeName = substring(B.ST_Style ,1,Len(A.PTT_PdtypeName))
GROUP BY A.PTT_PdtypeName
FROM Table1 A
LEFT OUTER JOIN Table2 B ON A.PTT_PdtypeName = LEFT(B.ST_Style,PATINDEX('%[0-9]%', B.ST_Style) - 1)
GROUP BY A.PTT_PdtypeName
from table1 a join table2 b on b.ST_Style like a.PTT_PdtypeName+'%'
group by a.PTT_PdtypeName
declare @table1 Table(PTT_ID int,PTT_PdtSerial int,PTT_PdtypeName varchar(4)
,PTT_Type varchar(10),PTT_Re varchar(10))
insert into @table1
select 1,4,'PAF','单机',NULL
union all select 2,3,'JAF','单机',NULL
union all select 3,4,'PF','单机',NULL
union all select 4,4,'PS','单机',NULLdeclare @table2 table(ST_ID int,ST_Name varchar(20),ST_Style varchar(30),ST_Number int)
insert into @table2
select 1,'平行轴斜齿轮减速机','PAF67-YB2.2-4P-16.83-H1-270',2
union all select 2,'平行轴斜齿轮减速机','PAF67-YB2.2-4P-16.83-H1-270',4
union all select 3,'平行轴斜齿轮减速机','PF32-YB1.2-4P-16.83-H1-270',7
union all select 4,'平行轴斜齿轮减速机','PF32-YB1.2-4P-16.83-H1-270',1
union all select 5,'平行轴斜齿轮减速机','JAF67-YB3.2-6P-16.83-H1-270',2
union all select 6,'平行轴斜齿轮减速机','JAF67-YB3.2-6P-16.83-H1-270',2--查询
select a.PTT_PdtypeName,ST_Number=sum(ST_Number)
from @table1 a join @table2 b on b.ST_Style like a.PTT_PdtypeName+'%'
group by a.PTT_PdtypeName/*--测试结果
PTT_PdtypeName ST_Number
-------------- -----------
JAF 4
PAF 6
PF 8(所影响的行数为 3 行)
--*/
,PTT_Type varchar(10),PTT_Re varchar(10))
insert into @table1
select 1,4,'PAF','单机',NULL
union all select 2,3,'JAF','单机',NULL
union all select 3,4,'PF','单机',NULL
union all select 4,4,'PS','单机',NULLdeclare @table2 table(ST_ID int,ST_Name varchar(20),ST_Style varchar(30),ST_Number int)
insert into @table2
select 1,'平行轴斜齿轮减速机','PAF67-YB2.2-4P-16.83-H1-270',2
union all select 2,'平行轴斜齿轮减速机','PAF67-YB2.2-4P-16.83-H1-270',4
union all select 3,'平行轴斜齿轮减速机','PF32-YB1.2-4P-16.83-H1-270',7
union all select 4,'平行轴斜齿轮减速机','PF32-YB1.2-4P-16.83-H1-270',1
union all select 5,'平行轴斜齿轮减速机','JAF67-YB3.2-6P-16.83-H1-270',2
union all select 6,'平行轴斜齿轮减速机','JAF67-YB3.2-6P-16.83-H1-270',2--查询
select a.PTT_PdtypeName,ST_Number=sum(ST_Number)
from @table1 a join @table2 b on charindex(PTT_PdtypeName,ST_Style)>0
group by a.PTT_PdtypeName