SQL Server - 如何删除重复的第二列

时间:2014-03-12 16:44:01

标签: sql-server

我的查询类似于以下内容并希望删除第二/第三列中的重复行...需要示例我可以使用以下内容(top 1,max,min等等)或不使用派生查询删除重复值的其他最佳方法。谢谢JK

WITH cteEMPAssistants (executive_personnel_number, assistant_personnel_number, assistant_type, SecType) AS
  (SELECT DISTINCT CASE
                       WHEN ISNUMERIC(KA.KIT_asgn_emplid) = 1 THEN CAST(CAST(KA.KIT_asgn_emplid AS INT) AS VARCHAR(11))
                       ELSE ''
                   END AS executive_personnel_number ,
                   CAST(CAST(KAP.emplid AS INT) AS VARCHAR(11)) AS assistant_personnel_number ,
                   ISNULL(LATT1.xlatlongname, '') AS assistant_type ,
                   CAST(LATT1.fieldvalue AS VARCHAR(4)) AS SecType ,
                   ISNULL(LATT3.xlatshortname, '') AS assign_role
   FROM dbo.KIT_ASGN_PRNT AS KAP
   LEFT OUTER JOIN dbo.KIT_ASSIGNMENTS AS KA ON KA.emplid = KAP.emplid
   AND KA.effdt = KAP.effdt
   LEFT OUTER JOIN dbo.KIT_EMPLOYEES AS EXECT ON EXECT.EMPLID = KA.KIT_ASGN_EMPLID
   LEFT OUTER JOIN dbo.KIT_EMPLOYEES AS ASST ON ASST.EMPLID = KAP.EMPLID
   LEFT OUTER JOIN dbo.XLATITEM AS LATT1 ON LATT1.fieldname = 'KIT_ASGN_TYPE'
   AND LATT1.fieldvalue = KAP.KIT_asgn_type
   LEFT OUTER JOIN dbo.XLATITEM AS LATT3 ON LATT3.fieldname = 'KIT_ASGN_ROLE'
   AND LATT3.fieldvalue = KA.KIT_asgn_role
   AND LATT3.xlatshortname = 'Primary'
   WHERE KAP.effdt =
       (SELECT MAX(effdt)
        FROM dbo.KIT_ASGN_PRNT
        WHERE emplid = KAP.emplid
          AND effdt <= GETDATE() ) --Return data only when employee and assistant  active; null is for temps

     AND (EXECT.EMP_STATUS = 'A'
          OR EXECT.EMP_STATUS IS NULL )
     AND ASST.EMP_STATUS = 'A' --Return all floating secretaries

     AND (KAP.KIT_asgn_type = 'F' --Return all assigned secretaries, who are assigned to a person and not a task

          OR (KAP.KIT_asgn_type IN ('A',
                                    'AF')
              AND KA.KIT_asgn_person = 'Y' ) ) )
SELECT CAST(EMP.KIT_EMPLID AS VARCHAR(15)) AS employeeNumber ,
       KAP.emplid AS Assistant ,
       SECRES.SecType AS SecType
FROM dbo.KIT_EMPLOYEES AS EMP
LEFT OUTER JOIN cteEMPAssistants AS SECRES ON EMP.KIT_EMPLID = SECRES.assistant_personnel_number
WHERE (EMP.EMP_STATUS = 'A')
  AND (EMP.PER_ORG IN ('EMP',
                       'CWR'))
  AND (ISNULL(EMP.KIT_NETWORK_ID, '') <> '')

以下是示例输出:

employeeNumber    Assistant     SecType
---------------   ---------     -----------------
1234               1112          A
1234               1112          A
1234               1112          A
1234               1112          A
4567               1113          NULL
1278               1114          NULL
1365               1115          NULL
1298               1116          A
1476               1117          A
1191               1118          NULL

1 个答案:

答案 0 :(得分:0)

您应该可以将此附加到查询的末尾:

GROUP BY EMP.KIT_EMPLID, KAP.emplid, SECRES.SecType