计算不同的重复项

时间:2016-08-12 09:23:53

标签: sql sql-server

我有以下查询:

WITH CTE AS(
   SELECT N, A, B,
   COUNT(*) OVER(PARTITION BY A, B) as cnt
   FROM Table
)
SELECT * FROM CTE WHERE cnt > 1

返回表中的所有重复计数。输出如下:

Table A (result of SQL)
N | A | B | cnt
----------------
1 | a | b | 2
1 | a | b | 2
1 | a | c | 1
1 | d | e | 2
2 | d | e | 2

我现在想要根据N(A& B相同,多于一个不同的N)选择重复值,所以:

Table B 
N | A | B | cnt
----------------
1 | d | e | 2
2 | d | e | 2

我是否应该在表A上再次应用上面的SQL代码来获取表B?或者有更简单的解决方案吗?

1 个答案:

答案 0 :(得分:1)

我建议:

WITH CTE AS (
      SELECT N, A, B,
             MIN(n) OVER (PARTITION BY A, B) as min_n,
             MAX(n) OVER (PARTITION BY A, B) as max_n
      FROM Table
     )
SELECT *
FROM CTE
WHERE min_n <> max_n;