1

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

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

    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
4

2 回答 2

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
于 2012-05-08T15:44:45.710 回答
0

您可以使用 Windowed 函数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规定应用哪种逻辑,即适用于个人或家庭。

于 2012-05-08T16:01:05.697 回答