简体   繁体   English

使用特定条件排除记录

[英]Excluding Records using specific conditions

I have a table as below我有一张如下表

ID ID Type类型 Part部分
CD1 CD1 Service服务 A一个
CD1 CD1 Service服务 null无效的
CD1 CD1 Service服务 B
CD1 CD1 Sales销售量 A一个
CD2 CD2 Service服务 null无效的
CD2 CD2 Sales销售量 B
CD3 CD3 Service服务 A一个
CD3 CD3 Service服务 null无效的

Output Required:输出要求:

ID ID Type类型 Part部分
CD1 CD1 Service服务 A一个
CD1 CD1 Service服务 B
CD1 CD1 Sales销售量 A一个
CD2 CD2 Service服务 null无效的
CD2 CD2 Sales销售量 B
CD3 CD3 Service服务 A一个

Explanation : For example CD1 has Service as Type with A,B and a null as Part, CD2 has Service as Type with only null as Part.解释:例如 CD1 的服务类型为 A、B,零件为 null,CD2 的服务类型为零件,零件只有 null。 Since CD1 has A,B as part, null value record has to be excluded and CD2 with Service as Type doesn't contain any values other than null it should not be excluded.由于 CD1 具有 A、B 作为一部分,因此必须排除空值记录,并且具有服务作为类型的 CD2 不包含除 null 以外的任何值,因此不应排除它。

Similarly CD3 has Service as Type with A and null as Part.类似地,CD3 将 Service 作为 Type,A 和 null 作为 Part。 Since A exists null value record has to be excluded.由于 A 存在,必须排除空值记录。

Is this possible to achieve using SQL?这可以使用SQL来实现吗?

Thanks in Advance提前致谢

You can assign a ranking using the ROW_NUMBER window function, where the null values will be assigned the least value.您可以使用ROW_NUMBER窗口函数分配排名,其中将为空值分配最小值。 Then you can select all rows from your table where the value is not null or the ranking is 1 (if null is found in first position, it will mean that it's the only value for that combination of ID and Type):然后,您可以从表中选择值不为 null 或排名为 1 的所有行(如果在第一个位置找到 null,则意味着它是 ID 和 Type 组合的唯一值):

WITH cte AS (
    SELECT *, 
           ROW_NUMBER() OVER(PARTITION BY ID, Type 
                             ORDER     BY Part DESC) AS rn
    FROM tab
)
SELECT ID,
       Type, 
       Part
FROM cte
WHERE Part IS NOT NULL 
   OR rn = 1

Try it here .在这里试试。

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

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