通过检查列值sql获取唯一行


青阳
2025-03-09 09:00:07 (11天前)


我是SQL的新手,所以如果你觉得这个问题很愚蠢,请原谅。


  • ——————– +
    id state isPresent

  • ——————– +
    id1 1 N.
    id2 2 N.
    id2 2 Y.
    id3 ……


4 条回复
  1. 0# ⑩Ⅵ嵗D夨憶 | 2019-08-31 10-32



    尝试使用内部联接,如下所示:




    1. SELECT DISTINCT(id)
      FROM table t1 INNER JOIN table t2
      ON t1.id = t2.id
      AND t1.isPresent != t2.isPresent
      WHERE state = 2

    2. </code>


    我们正在使用id字段相同而在表上进行内连接

    isPresent

    字段持有一个作为Y而另一个作为N.我将硬状态编码为2,但您可以对其进行参数化并在预编译语句中以编程方式使用它以动态传递它。


  2. 1# 梦中会飞的鱼 | 2019-08-31 10-32



    看起来很简单

    WHERE

    条款

    DISTINCT

    做你解释的。



    你需要第11 - 14行。




    1. SQL> with test (id, state, ispresent) as
      2 (select id1’, 1, N from dual union all
      3 select id2’, 2, N from dual union all
      4 select id2’, 2, Y from dual union all
      5 select id3’, 3, N from dual union all
      6 select id4’, 4, N from dual union all
      7 select id4’, 4, Y from dual union all
      8 select id5’, 2, N from dual union all
      9 select id5’, 2, Y from dual
      10 )
      11 select distinct id
      12 from test
      13 where ispresent = N
      14 and state = &par_id;
      Enter value for par_id: 2

    2. ID

      id2
      id5

    3. SQL> /
      Enter value for par_id: 4

    4. ID

      id4

    5. SQL>

    6. </code>

  3. 2# LOGO | 2019-08-31 10-32



    我想你想回归一个独特的

    id

    ,只要它有两种情况(

    N



    Y

    )同时为

    isPresent

    柱。因此,请考虑使用以下SQL语句

    exists

    操作员通过改变参数(现在是

    2

    ):




    1. with tab(id, state, isPresent) as
      (
      select id1’, 1, N union all
      select id2’, 2, N union all
      select id2’, 2, Y union all
      select id3’, 3, N union all
      select id4’, 4, N union all
      select id4’, 4, Y union all
      select id5’, 2, N union all
      select id5’, 2, Y
      )
      select distinct id
      from tab t1
      where exists ( select 1
      from tab t2
      where t2.state = t1.state
      and t2.isPresent in (‘N’,’Y’) this line might be commented out, if its certain that therere only two cases N and Y
      group by t2.state
      having count(distinct t2.isPresent) = 2
      )
      and t1.state = 2 try other values also such as 1, 3, 4

    2. </code>


    对于价值观

    1



    3

    不会返回任何行,而对于

    2



    4

    返回至少一行。





    Rextester演示



登录 后才能参与评论