按条款分组导致重复记录

时间:2019-08-22 15:57:58

标签: sql sql-server

我目前有以下查询,这给了我8位员工的重复条目。例如:

EMPLOYEE    FIRST_NAME  LAST_NAME   PL_1    PL_2    PL_3    PL_4    PL_5    PL_6 DUAL_EMPLOYEE  Dual_Process_Level_Comparison   process_level_compare
15723   BARBARA         FERREIRA                        LSBCW   LSBCR   NULL    NULL    NULL    NULL        NULL     
15723   BARBARA         FERREIRA                        LSBCW   NULL    NULL    NULL    NULL    NULL        NULL     

芭芭拉应该只有1条记录,并且看起来应该像这样:

15723   BARBARA         FERREIRA                        LSBCW   LSBCR   NULL    NULL    NULL    NULL        NULL     

我注意到a.process group by语句似乎有问题。

   select 
              a.EMPLOYEE, 
              m.FIRST_NAME, 
              m.LAST_NAME, 
              m.PROCESS_LEVEL as PL_1, 
              max(case when a.POS_LEVEL = 2 then a.process end) as PL_2, 
              max(case when a.POS_LEVEL = 3 then a.process end) as PL_3, 
              max(case when a.POS_LEVEL = 4 then a.process end) as PL_4, 
              max(case when a.POS_LEVEL = 5 then a.process end) as PL_5, 
              max(case when a.POS_LEVEL = 6 then a.process end) as PL_6, 
              case when s.[DUAL EMPLOYEE] = 'UNASSIGNED' then ' ' else s.[DUAL EMPLOYEE] end as DUAL_EMPLOYEE, 
              case when a.process = s.[DUAL EMPLOYEE] then 'REVIEW' end as Dual_Process_Level_Comparison, 

              case 
                when a.process in ('test') then 1 
                when a.process in ('test2', 'test3') then 2 
                   when a.process in ('test4', 'test5', 'test6') then 3 
                   when a.process in ('test7', 'test', 'LSBCW', 'LTBC', 'LTBH', 'LTBV', 'LTCLR', 'LTCS', 'LTHC', 'LTMON', 'LTSBC') then 4 
                   when a.process in ('hi') then 5 
                   when a.process in ('kkkkk') then 6 
                   when a.process in ('aaaa') then 7 
                   when a.process in ('ttttt') then 8 
                   when a.process in ('oooo') then 9 
                   when a.process in ('aaaaaa') then 10 
                   when a.process in ('testest', 'def', 'ghi') then 11 
              end as Supplemental_Compare_Number
            from 
              dbo.vw_PAEMPPOS a 
              join dbo.COMPLETE_EMPLOYEE_MASTER m on m.EMPLOYEE = a.EMPLOYEE 
              join dbo.HR_EMPUSERFIELDS s on s.EMPLOYEE = m.EMPLOYEE 

            where END_DATE = '2099-12-31 00:00:00.000' 
              and EMP_STATUS NOT IN ('1A', 'RT', 'SZ', 'T1', 'XD', 'XV', 'ZZ') 
            group by 
              a.EMPLOYEE, 
              m.LAST_NAME, 
              m.FIRST_NAME, 
              m.PROCESS_LEVEL, 
              s.[DUAL EMPLOYEE],
              a.process

我发现问题出在a.process分组依据,这给了我额外的员工价值。无论如何,我是否可以通过运行组中的a.process来使查询运行? dbo.vw_PROD.process在选择列表中无效,因为它没有包含在聚合函数中,或者GROUP BY子句是我收到的错误。

1 个答案:

答案 0 :(得分:2)

如果每个员工只需要一行,那么您的GROUP BY子句应为:

group by a.EMPLOYEE

期间。没有其他列,除非您知道每个员工只有一个值。因此,名称可能没问题。

在其余的列上使用适当的聚合列。您可以使用MIN()MAX()(两者之一)作为名称。