删除重复行但更改剩余副本上的列数据

时间:2012-05-08 15:21:27

标签: sql sql-server-2008 having-clause

我正在创建一个人员邮件列表,我将发送给打印店打印出来。我想出了如何取出所有重复的地址,但我需要一种方法,我可以将居住在重复地址的人的姓名更改为“姓氏”家庭。重复的地址告诉我,我有一个居住在那里的两个人的地址,所以我只发送两封邮件,而不是发送给他们两封邮件。提前致谢

这是我到目前为止所拥有的

    SELECT First_Name + ' ' + Last_Name AS Name, Mail_Address_1, phone
    FROM    Personal
    GROUP BY Mail_Address_1
    HAVING  COUNT(Mail_Address_1) > 1
    order by  Mail_Address_1

2 个答案:

答案 0 :(得分:0)

如果您想取出重复的行并修改剩余的行以识别它,您可以使用t

WITH DUPE (MAIL_ADDRESS_1)
AS
(
    SELECT MAIL_ADDRESS_1
        FROM    PERSONAL
        GROUP BY MAIL_ADDRESS_1
        HAVING  COUNT(MAIL_ADDRESS_1) > 1
)
SELECT FIRST_NAME, LAST_NAME , MAIL_ADDRESS_1, PHONE FROM PERSONAL WHERE MAIL_ADDRESS_1 NOT IN(
    SELECT MAIL_ADDRESS_1 FROM DUPE)
UNION
SELECT TOP 1 FIRST_NAME, LAST_NAME + '(DUPE MAIL)' AS LAST_NAME, MAIL_ADDRESS_1, PHONE 
FROM PERSONAL WHERE MAIL_ADDRESS_1 IN (SELECT MAIL_ADDRESS_1 FROM DUPE)

或简单的选择:

SELECT FIRST_NAME, LAST_NAME , MAIL_ADDRESS_1, PHONE FROM PERSONAL WHERE MAIL_ADDRESS_1 NOT IN(
    SELECT MAIL_ADDRESS_1
        FROM    PERSONAL
        GROUP BY MAIL_ADDRESS_1
        HAVING  COUNT(MAIL_ADDRESS_1) > 1
    )
UNION
SELECT TOP 1 FIRST_NAME, LAST_NAME + '(DUPE MAIL)' AS LAST_NAME, MAIL_ADDRESS_1, PHONE 
FROM PERSONAL WHERE MAIL_ADDRESS_1 IN (
    SELECT MAIL_ADDRESS_1
        FROM    PERSONAL
        GROUP BY MAIL_ADDRESS_1
        HAVING  COUNT(MAIL_ADDRESS_1) > 1
    )
ORDER BY  MAIL_ADDRESS_1

答案 1 :(得分:0)

您可以使用窗口函数ROW_NUMBER()COUNT(*) OVER()

来实现此目的
SELECT  CASE WHEN Duplicates = 1 THEN First_Name + ForeName ELSE 'The ' + Last_name + ' Household' END [Name]
        Mail_Address_1,
        Phone
FROM    (   SELECT  First_name, 
                    Last_name,
                    Mail_Address_1,
                    Phone,
                    ROW_NUMBER() OVER(PARTITION BY Mail_Address_1 ORDER BY Last_name) [RowNum],
                    COUNT(*) OVER(PARTITION BY Mail_Address_1) [Duplicates]
            FROM    Personal
            WHERE   Registered_Voter = 1
        ) p
WHERE   RowNum = 1

ROW_NUMBER()将结果限制为每个地址的顶部条目,COUNT指示应用哪种逻辑,即对个人或家庭。