我有两张表如下
Company Country
---------------------
abc 123 abc USA
def 456 def USA
ghi 789 ghi USA
Company State
------------------------
abc 123 TX
def 234 def def NY
ghi 789 AZ
我需要从表1中查询公司,并将前两个单词与tabl2中的Company进行比较,如果匹配则打印输出。 我已成功设法使用代码
从表1中获取前两个单词SELECT SUBSTRING (
tbSurvey.company,
0,
CHARINDEX (' ',
tbSurvey.company,
CHARINDEX (' ', tbSurvey.company, 0) + 1))
FROM tbSurvey;
我无法将列与表2中的公司列匹配。我正在尝试使用代码
SELECT endcustomername, endcustomercode, country
FROM tbLicense
WHERE EXISTS
(SELECT company, endcustomername, endcustomercode
FROM tbSurvey, tblicense
WHERE tbSurvey.company < tbLicense.endcustomername
AND tbSurvey.company <> ' '
AND tbLicense.endcustomercode LIKE
SUBSTRING (
tbSurvey.company,
0,
CHARINDEX (
' ',
tbSurvey.company,
CHARINDEX (' ', tbSurvey.company, 0) + 1))
+ '%');
但我没有得到所需的输出。请帮忙。
答案 0 :(得分:0)
嗯,它不是非常简洁和可读,但我认为它完成了你需要的工作
with cte_survey as (
select
t.*,
case when s.i > 0 then left(t.company, s.i - 1) else t.company end as k
from tbSurvey as t
outer apply (select charindex(' ', t.company) as i) as f
outer apply (select case when f.i > 0 then charindex(' ', t.company, f.i + 1) else len(company) end as i) as s
)
select
s.company as sur_compant, l.company as lic_company, s.country, l.[state] as [state]
from cte_survey as s
inner join tblicense as l on l.company = s.k
如果您想通过前两个单词比较两列:
with cte_survey as (
select
t.*,
case when s.i > 0 then left(t.company, s.i - 1) else t.company end as k
from tbSurvey as t
outer apply (select charindex(' ', t.company) as i) as f
outer apply (select case when f.i > 0 then charindex(' ', t.company, f.i + 1) else len(company) end as i) as s
),
cte_license as (
select
t.*,
case when s.i > 0 then left(t.company, s.i - 1) else t.company end as k
from tblicense as t
outer apply (select charindex(' ', t.company) as i) as f
outer apply (select case when f.i > 0 then charindex(' ', t.company, f.i + 1) else len(company) end as i) as s
)
select
s.company as sur_compant, l.company as lic_company, s.country, l.[state] as [state]
from cte_survey as s
inner join cte_license as l on l.k = s.k