在sql server中查找重复项

时间:2016-10-20 07:40:38

标签: sql sql-server duplicates

我有一个像这样的人......

BookId      BookName                                        BookProvider

1                   Angels and deamons                      Amazon
2                   Angels and deamons                      Amazon
3                   Angels and deamons                      Ebay
4                   Tuesdays                                Amazon                  
5                   SQL 101                                 Ebay                    

我想找到相同且存在于多个唯一BookProvider中的所有书名,我该如何在SQL查询中执行此操作?在这个例子中,我想检索记录1和2,因为书名相同,可以在亚马逊和ebay上找到。

6 个答案:

答案 0 :(得分:5)

试试这个

select  BookName from table
group by BookName
having count(distinct BookProvider)>1

答案 1 :(得分:1)

你想要整行吗,包括Bookid和BookProviders?有一个子查询,返回可以在多个商店中找到的书名。加入那个结果。

select t1.*
from tablename t1
join (select BookName from tablename
      group by BookName
      having count(distinct BookProvider) > 1) t2
    on t1.BookName = t2.BookName 

答案 2 :(得分:1)

这将返回同一BookProvider的多行所有书籍:

WITH cte AS
 (
   SELECT *, COUNT(*) OVER (PARTITION BY BookProvider, BookName) AS cnt 
   FROM @BookTable TT
 )
SELECT * 
FROM cte
WHERE cnt > 1;

答案 3 :(得分:0)

DECLARE @BookProvider TABLE(
    Id int
    ,BookName VARCHAR(100)
    ,BookProvider VARCHAR(100)
)

INSERT INTO @BookProvider
VALUES(1, 'Angels and Demons', 'Amazon')
INSERT INTO @BookProvider
VALUES(2, 'Angels and Demons', 'Ebay')
INSERT INTO @BookProvider
VALUES(3, 'Tuesdays', 'Amazon')
INSERT INTO @BookProvider
VALUES(4, 'SQL 101', 'Ebay')

SELECT BookName, COUNT(DISTINCT BookProvider) as Count FROM @BookProvider 
GROUP BY BookName
HAVING COUNT(DISTINCT BookProvider) > 1

结果:

+-------------------+-------+
|     BookName      | Count |
+-------------------+-------+
| Angels and Demons |     2 |
+-------------------+-------+

答案 4 :(得分:0)

这样:

select count(bookname),bookname from tablename group by bookname having count(bookname)>1

答案 5 :(得分:0)

如果您想要查看所有图书及其数量,您甚至可以使用带有分区的CTE:

DECLARE @BookTable TABLE
(
    BookId int,
    BookName varchar(100),
    BookProvider varchar(100)
)

INSERT INTO @BookTable
(
    BookId,
    BookName,
    BookProvider
)
VALUES
(1, 'Angel and Demons', 'Amazon'),
(2, 'Angel and Demons', 'EBay'),
(3, 'Tuesdays','Amazon'),
(4, 'SQL 101', 'Amazon');

WITH BookCte 
AS
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY TT.BookName ORDER BY TT.BookName) as RowNumber FROM @BookTable TT
)

SELECT * FROM BookCte BC