Exclude rows based on other rows (SQL)

后端 未结 4 473
你的背包
你的背包 2020-12-21 07:40

Say I have a query like this:

SELECT *
FROM TABLE

And it returns this:

TABLE
ID | DATA | VAL
===============
01 | ABCD | 1
         


        
相关标签:
4条回答
  • 2020-12-21 07:49

    you could use a minus operator.

    pseudo-query

    select everything
    from tables
    where id in ( select id from table minus select id from table where val is bad )
    
    0 讨论(0)
  • 2020-12-21 08:01

    you could try something like

    SELECT *
    FROM TABLE
    WHERE TABLE.ID NOT IN(
        SELECT ID
        FROM TABLE
        WHERE TABLE.VAL < '1'
        OR TABLE.VAL > '3'
    )
    
    0 讨论(0)
  • 2020-12-21 08:01

    Here is another alternative that will pass through TBL once, aggregate, and using the IDs found, retrieve the data from TBL

    SELECT *
    WHERE ID IN
    (
        SELECT
           ID,
           CASE WHEN val in (1,2,3) THEN 1 ELSE 0 END Test
        FROM TBL
        GROUP BY ID
        HAVING MIN(val) = 1
    )
    

    For multi-column keys, and as an alternative to the above IN form, you can use the JOIN form.

    SELECT T.*
    FROM (
        SELECT
           Company, OrderNumber,
           CASE WHEN val in (1,2,3) THEN 1 ELSE 0 END Test
        FROM TBL
        GROUP BY Company, OrderNumber
        HAVING MIN(val) = 1
        ) KEEP
    INNER JOIN TBL T ON T.Company = KEEP.Company and T.OrderNumber=KEEP.OrderNumber
    
    0 讨论(0)
  • 2020-12-21 08:10

    Use:

    SELECT * 
      FROM TABLE a
     WHERE a.val IN (1,2,3)
       AND NOT EXISTS(SELECT NULL
                        FROM TABLE b
                       WHERE b.id = a.id
                         AND b.val NOT IN (1, 2, 3))
    
    0 讨论(0)
提交回复
热议问题