Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To get the result that you want, you will need to use the <a href="http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx" rel="nofollow"><code>PIVOT</code></a> function. </p> <p>If all of your values (<code>title</code>) are known ahead of time, then you can hard-code a static query:</p> <pre><code>select * from ( select r.Title, f.UserName, f.Value from ReportItems r left join FormValues f on r.FormID = f.FormID and r.FieldID = f.FieldID ) src pivot ( max(value) for title in ([First Name], [Last Name], Age) ) piv; </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/514f2/4" rel="nofollow">SQL Fiddle with Demo</a>.</p> <p>But it sounds like you will have an unknown number of <code>titles</code> that you want to turn into columns. If that is the case, then you will want to use dynamic sql:</p> <pre><code>DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Title) from ReportItems FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT UserName,' + @cols + ' from ( select r.Title, f.UserName, f.Value from ReportItems r left join FormValues f on r.FormID = f.FormID and r.FieldID = f.FieldID ) x pivot ( max(value) for Title in (' + @cols + ') ) p ' execute(@query) </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/514f2/3" rel="nofollow">SQL Fiddle with Demo</a></p> <p>The result for both would be:</p> <pre><code>| USERNAME | FIRST NAME | LAST NAME | AGE | ------------------------------------------- | user 1 | Mike | Oscar | 20 | | user 2 | Merry | (null) | 23 | | user 3 | Alen | Escott | 28 | </code></pre> <p>If you have a specific <code>SortOrder</code> that you need and you have it stored in a table, then when you are getting your list of columns, you will use the following and it will return the columns in the correct order:</p> <pre><code>select @cols = STUFF((SELECT ',' + QUOTENAME(Title) from ReportItems group by Title, sortorder order by sortorder FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') </code></pre> <p>See <a href="http://sqlfiddle.com/#!3/b4626/4" rel="nofollow">SQL Fiddle with Demo</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload