[英]Finding duplicates with two similar columns and one distinct
我處於一種情況下,我需要在兩個特定的列中選擇具有相同內容的行,而在第三列中選擇具有不同內容的行。 到目前為止,我在兩個類似的列中都得到了這個:
SELECT id, Title,
COUNT(*) AS NumOccurrences
FROM Table
GROUP BY id, Title
HAVING ( COUNT(*) > 1 )
現在,我需要在此查詢中指定第三個不同的列。 我們稱它為拉爾夫(Ralph)。 這顯然行不通:
SELECT id, Title, DISTINCT Ralph,
COUNT(*) AS NumOccurrences
FROM Table
GROUP BY id, Title
HAVING ( COUNT(*) > 1 )
那會怎樣?
select * from (
SELECT id, Title, COUNT(*) AS NumOccurrences
FROM Table t
GROUP BY id, Title
HAVING ( COUNT(*) > 1 )
) t
cross apply (
select distinct Ralph
from Table
where id = t.id and Title = t.Title
) t2
您可以將COUNT(*)與OVER()子句一起使用
;WITH cte AS
(
SELECT id, Title, Ralph, COUNT(*) OVER (PARTITION BY id, Title) AS cnt
FROM dbo.test11
GROUP BY id, Title, Ralph
)
SELECT *
FROM cte
WHERE cnt > 1
關於SQLFiddle的演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.