如何创建SQL Distinct查询并添加一些其他字段

时间:2011-01-19 15:10:40

标签: sql sql-server-2005

我有以下查询,它选择名字和姓氏的组合并向我显示dupes。它有效,而不是问题。

我想包括其他三个字段以供参考; Id,cUser和cDate。但是,这些附加字段不应用于确定重复字段,因为我可能不会得到任何重复字段。

SELECT * FROM
(SELECT FirstName, LastName, COUNT(*) as "Count"
FROM Contacts
WHERE ContactTypeID = 1
GROUP BY LastName,FirstName
) AS X
WHERE COUNT > 1
ORDER BY COUNT DESC

有什么建议吗?谢谢!

2 个答案:

答案 0 :(得分:2)

SELECT  *
FROM    (
        SELECT  *, COUNT(*) OVER (PARTITION BY FirstName, LastName) AS cnt
        FROM    Contacts
        WHERE   ContactTypeId = 1
        ) q
WHERE   cnt > 1
ORDER BY
        cnt DESC

这将返回每个重复记录的所有字段。

答案 1 :(得分:0)

如果这些字段始终相同,那么您可以将它们包含在GROUP BY中,它不会影响重复项的检测

如果它们不是那么你必须决定你将在它们上应用什么样的聚合函数,例如MAX()或MIN()可以工作,并且会给你一些关于哪些值与某些属性相关联的指示重复。

否则,如果您想查看所有记录,可以加入回源

SELECT X2.* FROM
(SELECT FirstName, LastName, COUNT(*) as "Count"
FROM Contacts
WHERE ContactTypeID = 1
GROUP BY LastName,FirstName
) AS X INNER JOIN Contact X2 ON X.LastName = X2.LastName AND X.FirstName = X2.FirstName 
WHERE COUNT > 1
ORDER BY COUNT DESC