SQL 找到 table 有 diag_code 填充,然后在 lookup_table 中查找

SQL to find which table has diag_code filled, and then look it up in lookup_table

我有一个查询,diag_code 要么在一个 table (UM_SERVICE) 中,要么在另一个 (LOS) 中,但我不能同时加入两个 tables 得到 diag_code 这不是空的,我能想到的。这对于查找 diag_code 是否在 table 之一和查找 table 中是否合适?可能 LOS 和 UM_SERVICE 在不同的行上都有诊断代码,它们可能不同,并且两者或其中之一可能在查找 table 中。我在 Internet 搜索中没有看到任何内容。

这是一个简化的存储过程:

SELECT distinct
      c.id
      ,uc.id
      ,c.person_id 
    FROM dbo.CASES c 
    INNER JOIN dbo.UM_CASE uc with (NOLOCK) ON uc.case_id = c.id 
    LEFT JOIN dbo.UM_SERVICE sv (NOLOCK) ON sv.case_id =  omc.case_id 
    LEFT JOIN dbo.UM_SERVICE_CERT usc on usc.service_id = sv.id  
    LEFT JOIN dbo.LOS S WITH (NOLOCK) ON S.case_id = UC.case_id 
    LEFT JOIN dbo.LOS_EXTENSION SC WITH (NOLOCK) ON SC.los_id = S.id 
    INNER JOIN dbo.PERSON op with (NOLOCK) on op.id = c.Person_id
    WHERE
        (sv.diag_code is not null and c.case_id = sv.case_id
        or
        s.diag_code is not null and c.case_id = s.case_id)
      and     
        (sv.diag_code is not null and sv.diag_code in (select diag_code from TABLE_LOOKUP)
        or
        s.diag_code is not null and s.diag_code in (select diag_code from TABLE_LOOKUP)
Table setups like this:

    CASES
    id   person_id   
    
    UM_CASE
    case_id  
    
    LOS
    case_id  id
    
    LOS_EXTENSION
    los_id
    
    Person
    id    cid
    
    UM_SERVICE
    case_id     diag_code

    UM_SERVICE_CERT
    service_id    id

    TABLE_LOOKUP
    diag_code

由于您有两个不同的搜索 运行,通过单独编写搜索然后使用 [=11= 将两个结果集放在一起,write/read 会容易得多] 操作员。 UNION 将消除两个结果集中的重复项,其方式与您使用 SELECT DISTINCT 对单个结果集所做的类似。

像这样:

/*first part of union performs seach using filter on dbo.UM_SERVICE*/
SELECT 
    c.id
    ,uc.id
    ,c.person_id 
FROM 
    dbo.CASES AS c 
    INNER JOIN dbo.UM_CASE AS uc ON uc.case_id=c.id 
    LEFT JOIN dbo.UM_SERVICE AS sv ON sv.case_id =  omc.case_id 
    LEFT JOIN dbo.UM_SERVICE_CERT AS usc on usc.service_id=sv.id  
    LEFT JOIN dbo.LOS AS S ON S.case_id =  UC.case_id 
    LEFT JOIN dbo.LOS_EXTENSION AS SC ON SC.los_id= S.id 
    INNER JOIN dbo.PERSON AS op on op.id=c.Person_id
WHERE 
    sv.diag_code in (select diag_code from TABLE_LOOKUP) /*will eliminate null values in sv.diag_code*/
UNION /*deduplicate result sets*/
/*second part of union performs search using filter on dbo.LOS*/
SELECT 
    c.id
    ,uc.id
    ,c.person_id 
FROM 
    dbo.CASES AS c 
    INNER JOIN dbo.UM_CASE AS uc ON uc.case_id=c.id 
    LEFT JOIN dbo.UM_SERVICE AS sv ON sv.case_id =  omc.case_id 
    LEFT JOIN dbo.UM_SERVICE_CERT AS usc on usc.service_id=sv.id  
    LEFT JOIN dbo.LOS AS S ON S.case_id =  UC.case_id 
    LEFT JOIN dbo.LOS_EXTENSION AS SC ON SC.los_id= S.id 
    INNER JOIN dbo.PERSON AS op on op.id=c.Person_id
WHERE 
    s.diag_code in (select diag_code from TABLE_LOOKUP); /*will eliminate null values in s.diag_code*/