【问题标题】:SQL Select ALL ROWS but only if column value is uniqueSQL 选择所有行但仅当列值是唯一的
【发布时间】:2020-11-10 05:04:35
【问题描述】:

如果我执行以下操作:

select * from myTable

我明白了:

Column 1  | Column 2
---------------------
1         | Create
1         | Delete
2         | Create
3         | Create
4         | Create
4         | Delete
5         | Create

我想执行一个选择语句,我只提取第 1 列具有唯一编号的行

换句话说,我正在寻找这个结果:

Column 1  | Column 2
---------------------
2         | Create
3         | Create
5         | Create

不确定如何仅使用一个语句来实现这一点,或者是否有办法做到这一点。谢谢!

【问题讨论】:

    标签: sql count subquery where-clause


    【解决方案1】:

    如果没有重复的(column1, column2) 元组,一个选项是not exists

    select t.*
    from mytable t
    where not exists (
        select 1 from mytable t1 where t1.column1 = t.column1 and t1.column2 <> t.column2
    )
    

    【讨论】:

      【解决方案2】:

      你可以使用聚合:

      select col1, max(col2) as col2
      from t
      group by col1
      having count(*) = 1;
      

      如果给定值col1 只有一行,则max(col2) 将是该行上列的值。

      【讨论】:

        【解决方案3】:

        一个简单的查询来限制第 1 列的整数,计数不等于 1。

        SELECT col1, COUNT(col1), col2 
        FROM myTable
        WHERE count(col1) = 1
        GROUP BY col1
        

        【讨论】:

          【解决方案4】:
          Select column1, column2 from (select column1, column2, count(column1) over (PARTITION BY column2) count
          from myTable) where count = 1
          

          【讨论】:

            【解决方案5】:

            你可以使用 group by =

            select * from myTable where empno in (select empno val from myTable group by empno having COUNT(*) =1 )
            

            【讨论】:

              猜你喜欢
              • 2017-06-18
              • 2012-12-06
              • 2011-09-01
              • 1970-01-01
              • 2014-07-14
              • 2019-04-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多