title: Conditional group by in sql server?
body: <p>i have this simple query : </p>
  
  <pre><code>SELECT YEAR(P.DateCreated)
        ,MONTH(P.DateCreated)
        ,COUNT(*) AS cnt
  FROM   tbl1,
         tbl2....
  GROUP BY
           MONTH(P.DateCreated)
          ,YEAR(P.DateCreated)
  </code></pre>
  
  <p>this will emit : </p>
  
  <p><img src="https://i.stack.imgur.com/Euy9J.jpg" alt="enter image description here"></p>
  
  <p>now i need the same query but with groupby <strong>only</strong> per year : </p>
  
  <p>so :</p>
  
  <pre><code>SELECT YEAR(P.DateCreated)
  
        ,COUNT(*) AS cnt
  FROM   tbl1,
         tbl2....
  GROUP BY
           YEAR(P.DateCreated)
  </code></pre>
  
  <p>i <em>dont</em> want to make 2 queries.</p>
  
  <p>is there any way i can do conitional <code>group by</code> here ? </p>
  
  <p>i can do with <em>one being replaced by another</em> , but i <strong>cant</strong> do <em>one being replaced by two</em>...</p>
  
  <pre><code>GROUP BY
       CASE WHEN @timeMode='y' THEN YEAR(P.DateCreated)
            WHEN @timeMode='m' THEN MONTH(P.DateCreated), YEAR(P.DateCreated) end
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/HC5dK.jpg" alt="enter image description here"></p>
  
  <p>any help ?</p>