排除所有 id 相同的行,但具有相同 id 的行之一符合条件,而其他行不符合

时间:2021-05-17 16:11:42

标签: sql postgresql

如何过滤掉 id 相同的所有行,但具有相同 id 的行之一符合条件而其他行不符合条件?

create table people_table
        (
          ids varchar(30),
          id_code varchar(30),
          num_1 varchar(30)
        );

        insert into people_table values ('1','ABC','80');
        insert into people_table values ('2','ABC','80');
        insert into people_table values ('2','ZYX','81');
        insert into people_table values ('4','ABC','80');
        insert into people_table values ('4','DEF','80');
        insert into people_table values ('5','ABC','80');
        insert into people_table values ('6','ZYX','');

当前代码:

        SELECT people_table.*
FROM people_table
WHERE ids IN (SELECT ids
             FROM people_table
             WHERE (id_code between '123' AND '567')
                    AND ((num_1 = '80')
                    OR (num_1 = '' ))
             GROUP BY ids
             HAVING COUNT(ids)>=1)
AND id_code between '123' AND '567';

1 个答案:

答案 0 :(得分:1)

您可以尝试使用聚合窗口函数,编写您要排除的条件。然后过滤它们。

查询 1

SELECT ids,id_code,num_1,num_2
FROM (
  SELECT *,
        MAX(CASE WHEN id_code < '99201' OR id_code > '99499' 
                  AND ((num_1 = '25' OR num_2 = '25')
                    OR (num_1 = '25' OR num_2 = '')
                    OR (num_1 = '' OR num_2 = '25')) THEN 1 END) 
           OVER (PARTITION BY ids order by ids) exceptFlag
  FROM people_table 
) t1
WHERE exceptFlag IS NULL

Results

| ids | id_code | num_1 | num_2 |
|-----|---------|-------|-------|
|   1 |   99213 |    25 |       |
|   3 |   99213 |    25 |       |
|   3 |   99201 |       |       |
|   4 |   99213 |    25 |       |
|   4 |   99201 |    25 |       |
|   5 |   99213 |    25 |       |

如果您的列 id_code 存储数字值,我建议您使用数字类型。