用 case 实现 "not in" 到 select

Implement "not in" to select with case

我有 select:

select col1,
   case
    when col2 = 'AB' then col3
    else cols2
   end as colX,
col4,sum(col5) from table 1
where....
group by col1,
case
when col2 = 'AB' then col3
else cols2
end, col4

如何添加如下内容:col2 not in ('AA','BB')?

我无法将 col2 添加到我的 select,因为我的整个 select 语句中有几个连接。

将新条件放在 WHERE 子句中。此外,如果您切换到使用派生的 table,则不必将 case 表达式写两次。 (更容易编码而不会出错,更容易阅读,更容易维护。)

select col1, colX, col4, sum(col5)
from
(
    select col1,
           case when col2 = 'AB' then col3
                else cols2
           end as colX,
           col4,
           col5
    from table1
    where...
      and col2 not in ('AA', 'BB')
) dt
group by col1, colX, col4