简体   繁体   中英

Excluding all ID values based on criteria, with a one to many relationship - SQL

Apologies if I'm not phrasing this well. I've searched for some time but I somehow have been missing how to do this. It would be great if someone could point me in the right direction.

Basically, I have a table with 2 columns: Serv_No / Prd_Name

Each Serv_No (1,2,3,4,5 etc.) may have unlimited varying Prd_Name (A, B, C, D, AA, BB, CC etc.)

I want to only include a Serv_No where a Serv_No has Prd_Name = AA and Prd_Name <> BB . If a Serv_No has both A1 & B1 then exclude all instances of that Serv_No , even if the other rows with that Serv_No have a different Prd_Name .

Thanks

try this:

SELECT * FROM [TABLE] WHERE [serv_no] IN(
    SELECT [serv_no] FROM [TABLE]  GROUP BY [serv_no] having COUNT([serv_no])=1
) AND prd_name  = 'AA'

this will select all serv_no where they have only 1 prd_name and then filter table by them
you can change your condition by adding more conditions at end

This is usually done using GROUP BY/HAVING over CASEs:

select serv_no
from tab
group by serv_no
having -- include AA
       sum(case when prd_name = 'AA'          then 1 else 0 end)  = 1 
       -- AA plus at least 1 other row <> BB
   and sum(case when prd_name <> 'BB'         then 1 else 0 end) >= 2 
       -- exclude if both A1 & B1 are present
   and sum(case when prd_name in ('A1', 'B1') then 1 else 0 end) <> 2 

If you want to get the detail rows, not only the serv_no you can move the SUMs as a Windowed Aggregate using OVER (PARTITION BY serv_no) into the QUALIFY clause.

would this work? assuming when you say a1 & b1 you mean aa and bb:

SELECT
    aa.serv_no
FROM
    (SELECT 
        serv_no
    FROM
        t
    WHERE
        prd_name = 'aa') aa LEFT OUTER JOIN
    (SELECT DISTINCT 
        serv_no
    FROM
        t
    WHERE
        prd_name = 'bb') bb ON
    aa.serv_no = bb.serv_no
WHERE
    bb.serv_no IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM