选择具有相同ID但在另一列中具有不同值的行

时间:2018-04-12 14:26:05

标签: sql sql-server-2014

我有一个包含用户数据的表(PS_JOB)。 USER ID(USRID)在此表中可以有多于一行,因此可以在名为PER_ORG的另一列(在同一个表中)中具有不同的值。当相同的USRID有超过1行并且这些行包含PER_ORG或'EMP'和'CWR'中的值时,我只想显示'EMP'记录。它必须是这种特定的组合,因为我仍然想要包括USRLID在PS_JOB中仅包含1行且PER_ORG中的值为'CWR'的情况,以及在PER_ORG中只有1行且值为'EMP'的USRID(也是以后可能会将其他值添加到此字段中,但是现在我只将这两个值归于此列。)

下面是我的查询,它将识别具有多于1个不同PER_ORG值的行的USRID。我在将这个问题纳入我的大型查询(下面的第二篇)时遇到了麻烦,因为我仍然希望引入不属于这种情况的其他USRID。

此SQL将显示USRID具有多个行且具有不同PER_ORG值的所有行。我想修改它以专门查看当USRID具有'EMP'和'CWR'的不同值时:

 SELECT *
 FROM PS_JOB B
 WHERE B.USRID IN (SELECT USRID FROM PS_JOB GROUP BY USRID HAVING 
 COUNT(DISTINCT PER_ORG) > 1 )

 AND EFFDT = (SELECT MAX(B_ED.EFFDT) FROM PS_JOB B_ED 
    WHERE B.USRID = B_ED.USRID 
      AND B.USR_RCD = B_ED.USR_RCD 
      AND B_ED.EFFDT <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10)) 
 AND B.ACTION <> 'TER'
--AND PER_ORG = 'EMP'
ORDER BY USRID

我想在上面的查询中应用类似的逻辑,因为我仍想捕获其他数据(不属于上述情况):

   SELECT A.IMMUN_CODE, B.COMPANY, COUNT(*) AS 'COUNT_OF_EXAMS'
   FROM PS_HS_IMMUN A 
   LEFT OUTER JOIN (PS_JOB B INNER JOIN PS_EMPLMT_SRCH_QRY E1 ON (B.USRID = 
    E1.USRID AND B.EMPL_RCD = E1.EMPL_RCD )) ON A.USRID = B.USRID

   WHERE B.EFFDT = 
    (SELECT MAX(B_ED.EFFDT) FROM PS_JOB B_ED 
     WHERE B.USRID = B_ED.USRID 
     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.USRID = B_ES.USRID 
     AND B.EMPL_RCD = B_ES.EMPL_RCD 
     AND B.EFFDT = B_ES.EFFDT)
     AND A.HISTORY_ONLY <> 'Y' 
   GROUP BY  A.IMMUN_CODE,  B.COMPANY 

   UNION 

   SELECT 'ZTOTAL', '', COUNT ( D.USRID) 
   FROM (PS_HS_IMMUN D 
   LEFT OUTER JOIN (PS_JOB E INNER JOIN PS_EMPLMT_SRCH_QRY E1 ON (E.USRID = 
    E1.USRID AND E.EMPL_RCD = E1.EMPL_RCD )) ON D.USRID = E.USRID) 
   WHERE ( ( E.EFFDT = 
    (SELECT MAX(E_ED.EFFDT) FROM PS_JOB E_ED 
     WHERE E.USRID = E_ED.USRID 
      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.USRID = E_ES.USRID 
      AND E.EMPL_RCD = E_ES.EMPL_RCD 
      AND E.EFFDT = E_ES.EFFDT) 
    AND D.HISTORY_ONLY <> 'Y' ))

希望我的要求有意义,如果您想查看示例数据,请告诉我。我希望尽可能避免使用Common Table Expressions。

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解正确。因此,您需要PS_job表中的所有记录,然后对于per_org列中具有多个值的所有记录,您要优先考虑EMP&#39; EMP&#39;值,但是对于只有一个值的记录,还有其他值吗?

如果是这样,我将如何开始:

    SELECT 
    [USRID],
    [PER_ORG] = COALESCE([PER_ORG],[PER_ORG1])

    FROM (SELECT DISTINCT 
          [USRID],
          [PER_ORG] = CASE WHEN [PER_ORG] = 'EMP' THEN 'EMP' ELSE NULL END,
          [PER_ORG1] 
          FROM [PS_JOB] AS [T1]

          LEFT JOIN (SELECT DISTINCT [USRID],[PER_ORG1] = CASE WHEN PER_ORG 
           = 'CWR' THEN 'CWR' ELSE NULL END) AS [T2]
           [T1].[USRID] = [T2].[USRID]) AS [DATA]