简体   繁体   English

以一对多关系排除基于条件的所有ID值-SQL

[英]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 基本上,我有一个包含2列的表: 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.) 每个Serv_No (1、2、3、4、5等)可以具有无限变化的Prd_Name (A,B,C,D,AA,BB,CC等)

I want to only include a Serv_No where a Serv_No has Prd_Name = AA and Prd_Name <> BB . 我只想包含Serv_No ,其中Serv_No具有Prd_Name = AAPrd_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 . 如果Serv_No同时具有A1 & B1 ,然后排除的所有实例Serv_No ,即使与其他行Serv_No有不同的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 这将选择所有只有1个prd_name的serv_no,然后按它们过滤表
you can change your condition by adding more conditions at end 您可以通过在末尾添加更多条件来更改条件

This is usually done using GROUP BY/HAVING over CASEs: 通常通过在情况下使用GROUP BY / HAVING来完成此操作:

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. 如果要获取详细信息行,则不仅可以使用serv_no,还可以使用OVER(PARTITION BY serv_no)将SUM作为窗口聚合移动到QUALIFY子句中。

would this work? 这会工作吗? assuming when you say a1 & b1 you mean aa and bb: 假设当您说a1和b1时,您的意思是aa和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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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