SQL Server 2008 R2:删除单个事件记录。

时间:2015-09-30 04:12:24

标签: sql-server sql-server-2008-r2

我的下表有两列,如下所示:

CREATE TABLE test_lin
(
    Cola INT,
    Colb INT
);

INSERT INTO test_lin VALUES(1,2);
INSERT INTO test_lin VALUES(1,3);
INSERT INTO test_lin VALUES(1,4);
INSERT INTO test_lin VALUES(1,5);
INSERT INTO test_lin VALUES(1,3);
INSERT INTO test_lin VALUES(2,4);
INSERT INTO test_lin VALUES(2,6);
INSERT INTO test_lin VALUES(2,7);
INSERT INTO test_lin VALUES(2,4);
INSERT INTO test_lin VALUES(2,6);

注意:现在我只想显示那些重复多次的记录。就像我的情况(1,3),(2,4),(2,6)一样,记录在表格中重复出现。

enter image description here

我想从结果集中删除单个事件记录。单次出现的记录如下图所示。

enter image description here

3 个答案:

答案 0 :(得分:1)

试试这个:

  WITH cte AS 
 (SELECT cola, colb
  FROM test_lin
  GROUP BY cola, colb
  HAVING count(*) > 1)
  SELECT l.*
  from test_lin l INNER JOIN CTE ON 
       l.cola = cte.cola and l.colb=cte.colb

答案 1 :(得分:1)

WITH CTE as 
(
SELECT Cola,Colb,ROW_NUMBER() OVER(PARTITION BY Cola,Colb ORDER BY Cola) AS RN
FROM test_lin
)

SELECT T.* 
FROM test_lin T INNER JOIN  CTE C ON C.COLa = t.Cola and C.COLb = t.Colb and c.RN=2

答案 2 :(得分:0)

检查此样本,我从@Ala示例中获取并添加了一些内容:

1)第一个选项

select * from 
(
 SELECT *
  FROM test_lin
  GROUP BY cola, colb
  HAVING count(*) > 1
  ) cte
join test_lin l  ON 
 l.cola = cte.cola and l.colb=cte.colb

2)@Ala回答纠正。

;WITH cte AS 
 (SELECT cola, colb
  FROM test_lin
  GROUP BY cola, colb
  HAVING count(*) > 1)
  SELECT  l.*   --remove distinct only
  from test_lin l INNER JOIN CTE ON 
       l.cola = cte.cola and l.colb=cte.colb