SQL查找两列具有相同值的行

时间:2012-04-03 12:17:35

标签: sql database oracle

我在Oracle数据库中有3 columnsmytable,我想要only duplicate values in 2nd and 3rd column的记录。

SQL> select * from mytable;

column1      column2       column3

  A            50           50----required output
  A            10           20----have different values i.e. 10 and 20
  A            50           50----required output
  A            30           70----have different values i.e. 30 and 70
  B            20           20----required output
  B            40           30----have different values i.e. 40 and 30

我想要count(*)的以下输出:

 column1      column2       column3

  A            50           50
  A            50           50
  B            20           20

非常感谢任何帮助

3 个答案:

答案 0 :(得分:4)

select column1, count (*)
from mytable
where column2 = column3
group by column1, column2;

答案 1 :(得分:0)

从你的问题来看,不清楚主键,因为第一列中的A被重复多次。

您可以尝试以下操作:

 select column1, column2, column3, count(*) from 
mytable where column2 = column3 group by column1, column2, column3;

答案 2 :(得分:0)

以下是示例示例,我正在使用此SQL Server,但我确信此查询也可以在ORACLE中运行 示例:

Create table #Test (colA int not null, colB int not null, colC int not null, id int not null identity) on [Primary]
GO
INSERT INTO #Test (colA,colB,colC) VALUES (1,1,1)
INSERT INTO #Test (colA,colB,colC) VALUES (1,1,1)
INSERT INTO #Test (colA,colB,colC) VALUES (1,1,1)

INSERT INTO #Test (colA,colB,colC) VALUES (1,2,3)
INSERT INTO #Test (colA,colB,colC) VALUES (1,2,3)
INSERT INTO #Test (colA,colB,colC) VALUES (1,2,3)

INSERT INTO #Test (colA,colB,colC) VALUES (4,5,6)
GO
Select * from #Test
GO

select count(colA) as tot_duplicate_count , colA ,colB ,colC  from #Test where id <=
(Select Max(id) from #Test t where #Test.colA = t.colA and
#Test.colB = t.colB and
#Test.colC = t.colC)
group by colA ,colB ,colC 
having count(colA) > 1

此查询每个数据行的重复记录总数