title: SQL: Group By with Case Statement for multiple fields
body: <p>I am trying to write a GROUP BY clause with a CASE statement so I can conditionally GROUP BY according to the value of the parameter in my query. Here is my query that I am using (significantly shortened) and I keep getting "RVPname is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. And DVPname is invalid and AEname is invalid.</p>
  
  <pre><code>SELECT
  DVPname, RVPname, AEname, Dealer, Product, Distribution, 
  
  CASE WHEN @LEVEL = 'DVP' THEN DVPname
  WHEN @LEVEL = 'RVP' THEN RVPname
  WHEN @LEVEL = 'AE' THEN AEname
  END AS NAME
  
  ..........other code here.....
  
  GROUP BY Product, Distribution,
  CASE WHEN @LEVEL = 'RVP' THEN AEname WHEN @LEVEL = 'DVP' THEN RVPname WHEN @LEVEL= 'AE' THEN Dealer END
  </code></pre>
  
  <p>--Does anyone know how to do what I am trying to accomplish. When LEVEL='DVP' I want to GROUP BY RVPname, when LEVEL='RVP' I want to GROUP BY AEname....make sense?</p>