1

我处于需要选择在两个特定列中具有相同内容的行和在第三列中具有不同内容的行的情况。到目前为止,我为两个类似的列得到了这个:

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 )

那么会怎样呢?

4

2 回答 2

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
于 2013-02-20T10:50:00.043 回答
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上的演示

于 2013-02-20T11:09:08.903 回答