title: SQL GROUP BY with a SUM CASE statement
body: <p>I know that there are a lot of question like this:</p>
  
  <p><a href="https://stackoverflow.com/questions/1208854/sql-group-by-case-statement-with-aggregate-function">SQL GROUP BY CASE statement with aggregate function</a></p>
  
  <p>but I've tried doing:</p>
  
  <pre><code>with T as (select col1 , SUM(CASE WHEN col2 = 1 THEN col3 ELSE 0 END) AS Totale
     from tabella
     group by col1, col2)
  select col1, Totale
  from T
  group by col1, Totale 
  </code></pre>
  
  <p>but I'm getting</p>
  
  <pre><code>col1  |  Totale
  ---------------
     1       0
     1      70
     2       0
     2      90
  </code></pre>
  
  <p>Instead of:</p>
  
  <pre><code> col1  |  Totale
  ---------------
     1      70
     2      90
  </code></pre>
  
  <p>What's wrong with that?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>My bad, I try to keep it simple but I've overdone it.. What I've to do is:</p>
  
  <pre><code>with T as (select col1 , SUM(CASE WHEN col2 = 1 THEN col3 ELSE 0 END) AS TotaleA,
                           SUM(CASE WHEN col2 = 2 THEN col3 ELSE 0 END) AS TotaleB,
                            (...)
         from tabella
         group by col1, col2)
      select col1, TotaleA, TotaleB
      from T
      group by col1, TotaleA, TotaleB
  </code></pre>
  
  <p>And the solution is to do without col2 in the grouping... I was afraid getting "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause", but it's not.. Can I mark a comment as the correct answer?</p>