查询以比较表中列的前两个单词,并将其与另一个表中的另一列进行匹配

时间:2013-08-15 04:39:30

标签: sql sql-server

我有两张表如下

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))
                         + '%');

但我没有得到所需的输出。请帮忙。

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

sql fiddle demo

如果您想通过前两个单词比较两列:

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

sql fiddle demo