删除员工人口统计数据中的重复行数

时间:2015-08-19 15:52:37

标签: sql sql-server-2008 duplicates

我正在进行数据提取,以获取有关员工的人口统计信息 我遇到了失踪员工的问题,因为不是每个人都有电话号码(我 不知道为什么)

现在我有重复项,因为有些人有主要和非主要的电话号码。
它们可以被列为移动,家庭,工作等...我想要的是如果员工有一个主要电话号码列出它,但如果他们根本没有号码,我希望它被列出as" N / A"。

以下是我的查询。我很感激任何帮助。

SELECT  DISTINCT
        EJC.PersonTaxIdNo AS [SSN]
        ,EJC.EmpNo AS [Employee ID]
        ,ISNULL(EJC.Salutation, 'N/A') AS [Salutation]
        ,LTRIM(EJC.FirstName) AS [First Name]
        ,LTRIM(EJC.LastName) AS [Last Name]
        ,ISNULL(EJC.NameSuffix,'N/A') AS [Suffix]
        ,VPA.PersonAddress1 AS [Address]
        ,ISNULL(VPA.PersonAddress2,'') AS [Address 2]
        ,VPA.PersonAddressCity AS [City]
        ,VPA.PersonAddressStateAbbrev AS [State]
        ,VPA.PersonAddressPostalCode AS [Zip]
        ,CASE WHEN VPH.PersonPhonePrimaryInd = 1 AND (GETDATE() BETWEEN     VPH.PersonPhoneFromEffectDate AND VPH.PersonPhoneToEffectDate) THEN     VPH.PersonPhoneNo
            WHEN VPH.PersonPhoneNo IS NULL THEN 'N/A' END AS     [Primary Phone]
FROM CNKronos.CNKronos.dbo.EmployeeJob_Curr EJC
    LEFT JOIN CNKronos.CNKronos.dbo.vPERSON_ADDRESSES VPA
        ON EJC.PersonIdNo = VPA.PersonIdNo
    LEFT JOIN CNKronos.CNKronos.dbo.vPERSON_PHONES VPH
        ON EJC.PersonIdNo = VPH.PersonIdNo
WHERE VPA.PersonAddressPrimaryInd = 1
    AND GETDATE() BETWEEN VPA.PersonAddressFromEffectDate AND     VPA.PersonAddressToEffectDate
ORDER BY LTRIM(EJC.LastName), LTRIM(EJC.FirstName) 

PersonIdNo | PersonPhoneSeqNo | PersonPhoneTypeIdNo | PersonPhoneType | PersonPhonePrimaryInd | PersonPhoneNo | PersonPhoneExt | PersonPhoneFromEffectDate | PersonPhoneToEffectDate | PersonPhoneChangeDate   | PersonPhoneIsSmsSw | WTKPhoneIdNo   | Timestamp
71376      | 8129             | 23                  | Mobile          | 1                     | 123-456-7890  |                | 2013-11-21 00:00:00.000   | 3000-01-01 00:00:00.000 | 2014-04-10 20:58:53.450 | 0                  | 2              | 0x000000000503DB2E
71376      | 8130             | 21                  | Work            | 0                     | 234-567-8901  |                | 2013-11-21 00:00:00.000   | 3000-01-01 0:00:00.000  | 2014-04-10 20:58:53.760 | 0                  |   3              | 0x000000000503DB31

1 个答案:

答案 0 :(得分:0)

很难给你一个没有架构的解决方案。
所以我会尝试教你如何使用CTE Common Table Expressions

SQL FIDDLE DEMO

在小提琴中,您只需选择WITH内的代码即可查看部分结果。

该查询可以获得该日期范围内的有效手机。 User1有数据User2不

with current_phone as (
   SELECT u.name, p.*
   FROM 
       users u 
   left join phone p 
       on u.user_id = p.user_id
       and GETDATE() BETWEEN FromDate and ToDate
)
SELECT name, CASE 
                 WHEN phone is null then 'NA'
                 ELSE phone
             END as phone
FROM current_phone

您的想法是在CTE中进行小型计算,然后将结果与主表连接。希望能帮助您找到解决方案。

您也可以使用更好的架构更新sqlFiddle并告诉我。