title: Dynamic alternative to pivot with CASE and GROUP BY
body: <p>I have a table that looks like this:</p>
  
  <pre><code>id    feh    bar
  1     10     A
  2     20     A
  3      3     B
  4      4     B
  5      5     C
  6      6     D
  7      7     D
  8      8     D
  </code></pre>
  
  <p>And I want it to look like this:</p>
  
  <pre><code>bar  val1   val2   val3
  A     10     20 
  B      3      4 
  C      5        
  D      6      7     8
  </code></pre>
  
  <p>I have this query that does this:</p>
  
  <pre><code>SELECT bar, 
     MAX(CASE WHEN abc."row" = 1 THEN feh ELSE NULL END) AS "val1",
     MAX(CASE WHEN abc."row" = 2 THEN feh ELSE NULL END) AS "val2",
     MAX(CASE WHEN abc."row" = 3 THEN feh ELSE NULL END) AS "val3"
  FROM
  (
    SELECT bar, feh, row_number() OVER (partition by bar) as row
    FROM "Foo"
   ) abc
  GROUP BY bar
  </code></pre>
  
  <p>This is a very make-shifty approach and gets unwieldy if there are a lot of new columns to be created. I was wondering if the <code>CASE</code> statements can be made better to make this query more dynamic? Also, I'd love to see other approaches to doing this.</p>