title: Dynamic pivot query using PostgreSQL 9.3
body: <p>I have a table named as <code>Product</code>:</p>
  
  <pre><code>create table product (
      ProductNumber varchar(10),
      ProductName varchar(10),
      SalesQuantity int,
      Salescountry varchar(10)
  );  
  </code></pre>
  
  <p>Sample values:</p>
  
  <pre><code>insert into product values
    ('P1', 'PenDrive', 50,  'US')
  , ('P2', 'Mouse',    100, 'UK')
  , ('P3', 'KeyBoard', 250, 'US')
  , ('P1', 'PenDrive', 300, 'US')
  , ('P2', 'Mouse',    450, 'UK')
  , ('P5', 'Dvd',      50,  'UAE');   
  </code></pre>
  
  <p>I want to generate the <code>Salescountry's</code> names dynamically and show the sum of <code>SalesQuantity</code> sale in that Country.</p>
  
  <p>Expected result:</p>
  
  <pre><code>ProductName US    UK    UAE
  ----------------------------
  PenDrive    350   0     0
  Mouse       0     550   0
  KeyBoard    250   0     0
  Dvd         0     0     50
  </code></pre>
  
  <p><strong>I did it using SQL Server 2008 R2</strong>:</p>
  
  <pre><code>DECLARE @cols AS NVARCHAR(MAX),
          @query  AS NVARCHAR(MAX);
  
  SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(SalesCountry) 
              FROM Product
              FOR XML PATH(''), TYPE
              ).value('.', 'NVARCHAR(MAX)') 
          ,1,1,'')
  
  set @query = 'SELECT ProductName, ' + @cols + ' from 
              (
                  select ProductName
                      , SalesQuantity as q
                      , Salescountry
                  from Product
             ) x
              pivot 
              (
                   SUM(q)
                  for Salescountry in (' + @cols + ')
              ) p '
  
  PRINT(@query);
  execute(@query);
  </code></pre>
  
  <p>How to achieve this in Postgres?</p>