我目前使用#teacher
将#coursesCSV
与TeacherId
匹配,因此INNER JOIN
只有一个,我得到一行。获得此匹配后,我需要在同一行中显示该特定#coursesCsv.IsExpired
的可能TeacherId
。所以我匹配前3个字符和最后4个字符,但忽略中间的3个字符。根据这个标准,只有两个匹配,这就是为什么结果显示' OK / NOK'。此处的最大匹配数为2。
所以结果应如下所示:
teacherid isexpired WhatMatched
ABC-001-1225 OK OK/NOK
如果这太难了,另一个可能的结果就是计数:
teacherid isexpired WhatMatched
ABC-001-1225 OK 2
我一直在尝试获得一个' 2'对于WhatMatched
但是我一直得到3.而且我被困在那里。重要的是结果只能包含1行。
我这样做的原因是我们有一个使用#teacher.TeacherId
inner join
#coursesCSV
填充的网格,此行由用户评估和批准。在这种情况下,他自然会看到一行: ABC-001-1225 和确定。该网站不会让他批准,因为 NOK (ABC-002-1225)。我添加这个,以便他知道他需要检查一些东西而不必问我为什么他不能批准,因为它说 OK 。
这是查询:
IF OBJECT_ID('tempdb..#teacher') IS NOT NULL DROP TABLE #teacher
IF OBJECT_ID('tempdb..#coursesCsv') IS NOT NULL DROP TABLE #coursesCsv
create table #teacher
(
TeacherID varchar(20),
FullName varchar(30),
DeptId int
)
insert into #teacher select 'ABC-001-1225', 'Roy Brown', 3
create table #coursesCsv
(
IsExpired varchar(3),
TeacherID varchar(20),
DeptId int
)
insert into #coursesCsv select 'OK', 'ABC-001-1225', 3
insert into #coursesCsv select 'NOK', 'ABC-002-1225', 3
insert into #coursesCsv select 'OK', 'XYZ-002-1225', 3
select t.teacherid, c.isexpired, c.coursecnt, c.prefix
from #teacher t
inner join
(
select
teacherid,
left(teacherid, 3) as 'Prefix',
isexpired,
count(*)
over (partition by right(teacherid,4)) as coursecnt
from #coursesCsv
) as c
on t.teacherid = c.teacherid
and left(t.teacherid, 3) = left(c.teacherid, 3)
答案 0 :(得分:2)
我可能不理解这100%....但我认为你需要按teacherid
的前3个和后4个字符进行分区。所以......
select t.teacherid, c.isexpired, c.coursecnt, c.prefix
from #teacher t
inner join
(
select
teacherid,
left(teacherid, 3) as 'Prefix',
isexpired,
count(*)
over (partition by left(teacherid, 3), right(teacherid,4)) as coursecnt
from #coursesCsv
) as c
on t.teacherid = c.teacherid
and left(t.teacherid, 3) = left(c.teacherid, 3)