SQL在某些条件下加入两个表

时间:2018-01-17 16:58:00

标签: sql-server join

我有两张桌子。我想执行SQL连接,但无法弄清楚如何实现我的要求。以下是我的场景和我想要的结果。

情景-1

CountryDetails表 -

 StudyCode  Country   StudyId
 ABCDE123       AUS     null
 ABCDE123       IND     null
 ABCDE123       USA     null

StudyDetails表 -

 StudyCode    StudyId
 ABCDE123      1

加入后我想要的结果 -

 StudyCode  Country   StudyId
 ABCDE123       AUS     1
 ABCDE123       IND     1
 ABCDE123       USA     1

情景-2

CountryDetails表 -

 StudyCode  Country   StudyId
 ABCDE123       AUS     null
 ABCDE123       IND     null
 ABCDE123       USA     null

StudyDetails表 -

 StudyCode    StudyId
 ABCDE123      1
 ABCDE-123     2

加入后我想要的结果 -

 StudyCode  Country   StudyId
 ABCDE123       AUS     2
 ABCDE123       IND     2
 ABCDE123       USA     2

SQL内部联接 -

UPDATE C  
SET C.STUDYID=ST.StudyID 
FROM CountryDetails C     
INNER JOIN StudyDetails ST ON C.STUDYCODE=ST.StudyCode

此连接适用于第一种情况,但我无法弄清楚如何处理第二种情况。

编辑:

情景3:

CountryDetails表 -

 StudyCode  Country   StudyId
 ABCDE-123      AUS     null
 ABCDE-123      IND     null
 ABCDE-123      USA     null

StudyDetails表 -

 StudyCode    StudyId
 ABCDE123      1
 ABCDE-123     2

加入后我想要的结果 -

 StudyCode  Country   StudyId
 ABCDE-123      AUS     2
 ABCDE-123      IND     2
 ABCDE-123      USA     2

情景4:

CountryDetails表 -

 StudyCode  Country   StudyId
 ABCDE-123      AUS     null
 ABCDE-123      IND     null
 ABCDE-123      USA     null

StudyDetails表 -

 StudyCode    StudyId
 ABCDE123      1

加入后我想要的结果 -

 StudyCode  Country   StudyId
 ABCDE-123      AUS     1
 ABCDE-123      IND     1
 ABCDE-123      USA     1

1 个答案:

答案 0 :(得分:1)

此查询应涵盖两种情况

with cte as (
    select
        cd.StudyCode, cd.Country, sd.StudyId
    from
        CountryDetails cd
        join (
            select
                replace(StudyCode, '-', '') StudyCode, StudyId
                , row_number() over (partition by replace(StudyCode, '-', '') order by iif(charindex('-', StudyCode) > 0, 1, 2)) rn
            from
                StudyDetails
        ) sd on cd.StudyCode = sd.StudyCode and rn = 1
)

update CountryDetails
set CountryDetails.StudyId = cte.StudyId
from
    CountryDetails
    join cte on CountryDetails.StudyCode = cte.StudyCode and CountryDetails.Country = cte.Country

编辑:您的方案3和4与以前的方案没有太大差别。您只需要更改连接条件:

with cte as (
    select
        cd.StudyCode, cd.Country, sd.StudyId
    from
        CountryDetails cd
        join (
            select
                replace(StudyCode, '-', '') StudyCode, StudyId
                , row_number() over (partition by replace(StudyCode, '-', '') order by iif(charindex('-', StudyCode) > 0, 1, 2)) rn
            from
                StudyDetails
        ) sd on replace(cd.StudyCode, '-', '') = sd.StudyCode and rn = 1
)

update CountryDetails
set CountryDetails.StudyId = cte.StudyId
from
    CountryDetails
    join cte on CountryDetails.StudyCode = cte.StudyCode and CountryDetails.Country = cte.Country