使用SQL查询消除重复项

时间:2017-10-12 14:18:03

标签: sql-server duplicates common-table-expression

几个月前,我问过问题here。我现在遇到问题,我的客户告诉我他们缺少数据。我回过头来查看下面的查询,发现在删除P.NUMBERVALUE或完全删除电话号码时,会显示缺失的数据。但是,从查询中删除电话号码完全违背了使用此CTE的目的。我唯一能想到的是,如果一个记录根本没有电话号码,它就没有被选中。

我的问题是,如何获取所有记录并尽可能避免重复行。此查询的结果将成为我必须用于将记录导入CRM并且不能重复的CSV。与往常一样,非常感谢提供的任何帮助。

WITH CTE AS 
(
    SELECT DISTINCT
        C.COMPANYID AS 'Account CRM ID',
        C.NAME AS 'Company Name',
        --  P.NUMBERVALUE AS Phone,
        A.LINE1 AS 'Street',
        A.LINE2 AS 'Suite # / Unit # / Other',
        A.CITY AS 'City',
        A.STATE AS 'State',
        A.POSTALCODE AS 'Zipcode',
        C.CUST_County_111923725 AS 'County',
        C.CATEGORY AS 'Lead Category',
        C.NUMEMPLOYEES AS 'Number of Employees',
        C.INDUSTRY AS 'Industry Type',
        C.REVENUE AS 'Revenue',
        C.CUST_FrequencyofService_111240157 AS 'Schedule Frequency',
        C.WEBADDRESS AS 'Website',
        C.CUST_GeneraleMail_112218273 AS 'General Email',
        C.CUST_TypeofService_110014852 AS 'Service Type',
        C.CUST_CurrentMethod_111527894 AS 'Current Method',
        C.CREATEDATE AS 'Create Date',
        C.CUST_Comments_111653133 AS 'Company Comments'
        --ROW_NUMBER() OVER(PARTITION BY C.COMPANYID ORDER BY P.NUMBERVALUE) AS RN
    FROM 
        TBL_COMPANY C
    --JOIN TBL_PHONE P ON P.COMPANYID = C.COMPANYID
    JOIN 
        TBL_ADDRESS A ON A.COMPANYID = C.COMPANYID
)
SELECT 
    [Account CRM ID],
    [Company Name],
    -- Email,
    --MAX(CASE
    --        WHEN RN = 1
    --        THEN Phone
    --    END) AS Phone1,
    --MAX(CASE
    --        WHEN RN = 2
    --        THEN Phone
    --    END) AS Phone2,
    --MAX(CASE
    --        WHEN RN = 3
    --        THEN Phone
    --    END) AS Phone3,
    Street,
    [Suite # / Unit # / Other],
    City,
    State,
    Zipcode,
    County,
    [Lead Category],
    [Number of Employees],
    [Industry Type],
    [Revenue],
    [Schedule Frequency],
    Website,
    [General Email],
    [Service Type],
    [Current Method],
    [Create Date],
    [Company Comments]
FROM 
    CTE
WHERE 
    DATALENGTH(Street) > 0
GROUP BY 
    [Account CRM ID], [Company Name],
    --  Email,
    Street, [Suite # / Unit # / Other],
    City, State, Zipcode, County,
    [Lead Category],
    [Number of Employees],
    [Industry Type], [Revenue],
    [Schedule Frequency],
    Website,
    [General Email], [Service Type],
    [Current Method], [Create Date],
    [Company Comments]
ORDER BY 
    [Company Name];  

0 个答案:

没有答案