在联合查询中仅显示1行,其中在另一个表中具有某些条件的行

时间:2018-04-11 17:28:57

标签: sql sql-server-2014

我无法想到这个帖子的更好的标题,但是我有以下的Unioned查询,即每个UserID提取的考试信息,这些用户ID将被合并以提取总数。

问题在于,当UserID在PS_JOB中有两行时,一行的PER_ORG值为' CWR'另一行的PER_ORG值为' EMP'然后查询为此相同的UserID返回2行。在这种情况下,我只想显示' EMP'记录,这样只有1个ID(落入这个场景)的实例将计入我的总计(ZTOTAL)。

我想我需要某种带有NOT EXISTS的WHERE条件,它找到两行具有相同UserID的行, AND 一行包含PER_ORG =' EMP'而另一行包含PER_ORG =' CWR',但我正在努力解决如何编码。我不想排除在PS_JOB中有两行的USERID,其中包含PER_ORG的任何其他值组合,而不是' EMP'和' CWR'。

当前SQL:

SELECT 
    A.USERID, 
    A.IMMUN_CODE, 
    B.COMPANY, 
    COUNT(*) AS 'COUNT_OF_EXAMS'
FROM 
    PS_HS_IMMUN A,
    PS_JOB B,
    PS_EMPLMT_SRCH_QRY B1 
WHERE 
    (B.USERID = B1.USERID 
    AND B.EMPL_RCD = B1.EMPL_RCD 
    AND B1.OPRID = 'GG125' 
    AND (   A.USERID = B.USERID 
            AND B.EFFDT =   (SELECT MAX(B_ED.EFFDT)
                             FROM PS_JOB B_ED 
                             WHERE B.USERID = B_ED.USERID 
                             AND B.EMPL_RCD = B_ED.EMPL_RCD 
                             AND B_ED.EFFDT <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10)) 
            AND B.EFFSEQ =  (SELECT MAX(B_ES.EFFSEQ) 
                             FROM PS_JOB B_ES 
                             WHERE B.USERID = B_ES.USERID 
                             AND B.EMPL_RCD = B_ES.EMPL_RCD 
                             AND B.EFFDT = B_ES.EFFDT)
        )
    ) 
   AND A.HISTORY_ONLY <> 'Y' 
GROUP BY  A.USERID, A.IMMUN_CODE,  B.COMPANY 

UNION 

SELECT 
    'ZTOTAL', 
    '', 
    '', 
    COUNT ( D.USERID) 
FROM 
    (PS_HS_IMMUN D 
    LEFT OUTER JOIN 
        (PS_JOB E 
        INNER JOIN PS_EMPLMT_SRCH_QRY E1 ON 
        (E.USERID = E1.USERID 
         AND E.EMPL_RCD = E1.EMPL_RCD 
         AND  E1.OPRID = 'GG125' )) ON  
    D.USERID = E.USERID) 

WHERE 
    (
        (E.EFFDT =      (SELECT MAX(E_ED.EFFDT) 
                        FROM PS_JOB E_ED 
                        WHERE E.USERID = E_ED.USERID 
                        AND E.EMPL_RCD = E_ED.EMPL_RCD 
                        AND E_ED.EFFDT <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10)) 
        AND E.EFFSEQ = (SELECT MAX(E_ES.EFFSEQ) 
                        FROM PS_JOB E_ES 
                        WHERE E.USERID = E_ES.USERID 
                        AND E.EMPL_RCD = E_ES.EMPL_RCD 
                        AND E.EFFDT = E_ES.EFFDT) 
     --AND D.EXAM_DT BETWEEN :1 AND :2 
     --AND E.COMPANY = :3 
        AND D.HISTORY_ONLY <> 'Y' )
    )

以上查询的当前结果:

enter image description here

在此示例中,UserID 4992的两行是重复的,因为UserID在PS_JOBS表中有两行,因此USERID在查询中显示两次(最终在总计中计算两次)的原因。

如果我从PS_JOBS查询此USERID,您会看到此USERID的两行 AND PER_ORG状态为&#39; EMP&#39;尊敬的&#39; CWR&#39;

 SELECT *
 FROM PS_JOB
 WHERE EMPLID = '4992'

以上查询的结果:

enter image description here

我希望避免使用Common Table Expressions作为解决方案。谢谢你的任何建议!

0 个答案:

没有答案