Exclude rows based on other rows (SQL)

后端 未结 4 472
你的背包
你的背包 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 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
    

提交回复
热议问题