SELECT使用GROUP BY和HAVING不返回记录

时间:2012-07-16 18:28:02

标签: sql sql-server tsql

我正在尝试选择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编写的

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

您的Group By子句将按列表中的所有列进行分组。这些列可能定义了count = 1

的离散记录

您需要执行以下操作:

Select LAST_NAME from TM_USER  GROUP BY LAST_NAME HAVING COUNT(LAST_NAME) > 1

答案 2 :(得分:1)

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

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

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

如果按几列分组,即使计算COUNT超过单列值,也会计算其唯一组合。