title: How to select columns in a loop with conditions
body: <p>I have this query. DDIFF is just a difference of two Date columns in the table:</p>
  
  <pre><code>SELECT 
      DDIFF,
      SUM(CASE WHEN Franchise = 'Franchise' THEN 1 ELSE 0 END) AS [Franchise Count],
      SUM(CASE WHEN Franchise = 'Own' THEN 1 ELSE 0 END) AS [Own Count]
  FROM
      dbo.joined
  GROUP BY
      DDIFF, Franchise
  ORDER BY
      DDIFF
  </code></pre>
  
  <p>And this is a fragment of the output:</p>
  
  <pre><code>DDIFF   Franchise Count Own Count
  ----------------------------------
  NULL    0               1
  -31     0               3
  -28     0               13
  -20     2               0
  -16     1               0
  -13     0               2
  ...
  </code></pre>
  
  <p>I'm getting sales data made for Franchises or 'Own' shops.</p>
  
  <p>But I want to get these counts divided to months, so I need to make some kind of loop to get this two column for every month of the year (meaning 12x2 columns)</p>
  
  <p>To have something like this:</p>
  
  <pre><code>DDIFF   [2019.01 Franchise] [2019.01 Own] [2019.02 Franchise] [2019.02 Own] ...
  -------------------------------------------------------------------------
  NULL    0                   1             0                   1
  -31     0                   0             2                   1
  -28     0                   10            0                   3
  -20     1                   0             1                   0
  -16     1                   0             0                   0
  -13     0                   1             0                   1
  ...
  </code></pre>
  
  <p>I guess I need to creat some kind of loop and add an <code>AND dateColumn = year.month</code> condition at the <code>CASE WHEN</code> ... to build the actual column for that month, or even an embedded loop to cover multiple years.</p>
  
  <p>Is there a syntax which lets me create columns like this? </p>