title: TSQL - row values to column headings including further column values
body: <p>my input is a View with the following columns:</p>
  
  <pre><code>DOCID   DATE    ROWNUMBER   COLUMN1     COLUMN2     COLUMN3     COLUMN4     COLUMN5
  ABC000123   2014-04-11  1   approval    project name    ABC     (null)      (null)
  </code></pre>
  
  <p>The records of <strong>COLUMN2</strong> need to become <strong>column headings</strong> with <strong><em>either</em></strong> a value of COLUMN3 or COLUMN4. If COLUMN3 is empty or null then use COLUMN4.
  At the moment COLUMN5 is completely empty so you can ignore this column.</p>
  
  <p>The thing is that not every <strong>DocID</strong> contains all the values in <strong>COLUMN2</strong> that are needed to build the headings.</p>
  
  <p>So I thought using something like "<code>SELECT DISTINCT column2 AS headings</code>" over all entries of the View and then using the pivot function could get me somewhere.
  But I couldn't get it to work.</p>
  
  <p>I also need to be able to select only certain column heading regarding COLUMN2. Maybe this is easier once I have a view with all columns to choose from and create a new view from that.</p>
  
  <p>Have a look at this <strong>sample</strong>
  <a href="http://sqlfiddle.com/#!6/df226/1/0" rel="nofollow">Fiddle</a></p>
  
  <p>I use MSSQL 2012.</p>
  
  <p>I'd be happy for some sample code.</p>
  
  <p>Thank you.</p>