2016-10-20 153 views
0

我有一個這樣的talble ..查找重複在SQL Server

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上找到。

+0

是否要在結果中包含BookProviders? – jarlh

+0

你可以舉一個例子或更多的細節,它不明確 – mhmd

+1

你想要第1和第2行嗎?不是3? – jarlh

回答

1

此方法返回多行所有書籍一樣BookProvider:

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

謝謝,這解決了我的問題:) – MTplus

5

試試這個

select BookName from table 
group by BookName 
having count(distinct BookProvider)>1 
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 | 
+-------------------+-------+ 
0

這樣的:

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

對不起,我在第一個問題上犯了一個錯誤,我需要它基於獨特的Book提供者。我更新了最初的帖子.. – MTplus

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 
0

如果要查看所有的書和他們的計數你甚至可以使用一個CTE與partion還有:

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