【问题标题】:SQL to find rows where two columns have the same valueSQL查找两列具有相同值的行
【发布时间】:2012-04-03 12:17:35
【问题描述】:

我在 Oracle 数据库中有 3 columns 有表 mytable 并且我想要有 only duplicate values in 2nd and 3rd column 的记录。

SQL> 从我的表中选择 * ;

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

非常感谢任何帮助

【问题讨论】:

  • 是 column1 是主键,不能为空
  • 主键在其定义中是唯一的。这里column1 不是唯一的,是不是示例数据中的错误?
  • @MichałPowaga 抱歉抱歉没有主键
  • @Randy 抱歉抱歉没有主键

标签: sql database oracle


【解决方案1】:
select column1, count (*)
from mytable
where column2 = column3
group by column1, column2;

【讨论】:

    【解决方案2】:

    根据您的问题,主键不清楚,因为第一列中的A 被重复了很多次。

    您可以尝试以下方法:

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

    【讨论】:

      【解决方案3】:

      这是示例示例,我正在执行此 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
      

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

      【讨论】:

        猜你喜欢
        • 2016-01-27
        • 2016-05-21
        • 2021-08-02
        • 2017-01-13
        • 1970-01-01
        • 2014-07-14
        • 2018-05-07
        • 1970-01-01
        • 2017-02-10
        相关资源
        最近更新 更多