0

次のように2つのテーブルがあります

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 から Company をクエリし、最初の 2 つの単語を tabl2 の Company と比較し、一致する場合は出力を出力する必要があります。コードを使用して、表1から最初の2つの単語を取得することに成功しました

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

しかし、目的の出力が得られません。助けてください。

4

1 に答える 1

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 フィドルのデモ

両方の列を最初の 2 語で比較する場合:

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 フィドルのデモ

于 2013-08-15T05:56:18.637 に答える