我处于这样一种情况,我需要选择在两个特定列中具有相同内容的行,并在第三个列中选择不同的内容。到目前为止,我在两个类似的专栏中得到了这个:
SELECT id, Title,
COUNT(*) AS NumOccurrences
FROM Table
GROUP BY id, Title
HAVING ( COUNT(*) > 1 )
我现在需要在此查询中指定第三个不同的列。我们称之为拉尔夫。这显然不起作用:
SELECT id, Title, DISTINCT Ralph,
COUNT(*) AS NumOccurrences
FROM Table
GROUP BY id, Title
HAVING ( COUNT(*) > 1 )
那会是什么?
答案 0 :(得分:0)
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
答案 1 :(得分:0)
您可以将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上的演示