0

I have 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

How to the where add something like: col2 not in ('AA','BB')?

I can't add col2 to my select, because I have couple of joins in my whole select statement.

abarisone
  • 3,707
  • 11
  • 35
  • 54
4est
  • 3,010
  • 6
  • 41
  • 63

1 Answers1

1

Put the new condition in the WHERE clause. Also, if you switch to use a derived table, you don't have to write that case expression twice. (Easier to code without errors, easier to read, easier to maintain.)

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
jarlh
  • 42,561
  • 8
  • 45
  • 63