0

我正在尝试选择在 LASTNAME 列中具有重复值的所有记录。到目前为止,这是我的代码

If EXISTS( SELECT name FROM sysobjects WHERE name = 'USER_DUPLICATES' AND type = 'U' ) 
    DROP TABLE USER_DUPLICATES
GO

CREATE TABLE USER_DUPLICATES
(
    FIRSTNAME VARCHAR(MAX),
    LASTNAME VARCHAR(MAX),
    PHONE VARCHAR(MAX),
    EMAIL VARCHAR(MAX),
    TITLE VARCHAR(MAX),
    LMU VARCHAR(MAX)
)
GO

INSERT INTO USER_DUPLICATES
(
    FIRSTNAME,
    LASTNAME,
    PHONE,
    EMAIL,
    TITLE,
    LMU
)
SELECT
    FIRSTNAME,
    LASTNAME,
    PHONE,
    EMAIL,
    TITLE,
    LMU
FROM TM_USER
GROUP BY
    FIRSTNAME,
    LASTNAME,
    PHONE,
    EMAIL,
    TITLE,
    LMU
HAVING COUNT(LASTNAME) > 1

它不返回任何记录。我改变了

HAVING COUNT(LASTNAME) > 1

HAVING COUNT(LASTNAME) > 0

它返回所有记录。我也确定有些记录具有相同的 LASTNAME 值。它是在 SQL Server 上使用 T-SQL 编写的

4

3 回答 3

2

试试这个:

SELECT
    a.FIRSTNAME,
    a.LASTNAME,
    a.PHONE,
    a.EMAIL,
    a.TITLE,
    a.LMU
FROM TM_USER a
INNER JOIN
(
    SELECT LASTNAME
    FROM TM_USER
    GROUP BY LASTNAME
    HAVING COUNT(1) > 1
) b ON a.LASTNAME = b.LASTNAME
于 2012-07-16T18:40:45.357 回答
2

您的 Group By 子句将按列表中的所有社区分组。这些列可能定义了 count = 1 的谨慎记录

您将需要执行以下操作:

Select LAST_NAME from TM_USER  GROUP BY LAST_NAME HAVING COUNT(LAST_NAME) > 1
于 2012-07-16T18:43:23.423 回答
1

COUNT 函数是针对所有分组表达式计算的,而不是针对 LASTNAME。

要获得唯一的姓氏,请使用

SELECT LASTNAME FROM TM_USER GROUP BY LASTNAME HAVING COUNT(LASTNAME) > 1

如果您按几列分组,即使在单列值上计算 COUNT,您也会得到它们唯一组合的计数。

于 2012-07-16T18:44:59.007 回答