試試這個:
SELECT Users,Count(DISTINCT Books) as CountOfBooks
FROM TableName
GROUP BY Users
HAVING COUNT(DISTINCT Books) >= 2
說明:
在這裏,我們分組與用戶字段的表內容和計算的不同圖書的數量每個用戶都有。 HAVING
子句有助於用不同書的計數來過濾結果。
您可以根據需要更改數字2。而=
可用於精確匹配而不是至少。
查看SQL Fiddle中的示例。
編輯:
爲了排除用戶book_4,試試這個:
SELECT Users,Count(DISTINCT Books) as CountOfBooks
FROM TableName
WHERE Users NOT IN (SELECT Users FROM TableName WHERE Books = 'book_4')
GROUP BY Users
HAVING COUNT(DISTINCT Books) >= 2
或一個更快的版本(不使用IN
):
SELECT T1.Users,Count(DISTINCT T1.Books) as CountOfBooks
FROM TableName T1 LEFT JOIN
(SELECT Users
FROM TableName
WHERE Books = 'Book4') T2 ON T2.Users=T1.Users
WHERE T2.Users IS NULL
GROUP BY T1.Users
HAVING COUNT(DISTINCT T1.Books)>=2
中的一個例子SQL Fiddle。
分組由&與不同 – AK47
你能看到圖片嗎? – noors
是的。你能看到答案嗎? – AK47