在 SQL 中的 group by 子句后根据优先级过滤行

Filter rows based on priority after group by clause in SQL

按 id 在 table 下分组后,我想根据条件过滤行

输入table:

编号 选项
1 132
1 156
1 134
2 145
2 132
3 123
3 132
3 135
3 188

如果一个组包含 134 和 132,则只应过滤包含 134 的行。而该组仅包含 132,则必须选择它。 table 以外选项的行保持不变。

条件如下

一组选项的组合 必须保留组中具有以下选项值的行
132,134 134
132 132
132,135 135
132,136 136

输出table:

编号 选项
1 134
2 145
2 132
3 123
3 135
3 188

如果我没理解错的话,你是说当“132”也在组中时,“134”应该是唯一的元素。

select t.*
from (select t.*,
             sum( case when options = 132 then 1 else 0 end ) over (partition by id) as num_132,
             sum( case when options = 134 then 1 else 0 end ) over (partition by id) as num_134
      from t
     ) t
where num_132 = 0 or num_134 = 0 or options = 134