Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In order to get this result, 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. This transforms the data from multiple rows into columns.</p> <p>If you know the values ahead of time or you will have a limited number of <code>TestId</code> values, then you can hard-code the query making the query static.</p> <pre><code>SELECT Name, Age, [1] AS Test1, [2] AS Test2, [3] AS Test3 FROM ( SELECT P.Name, P.Age, t.TestID, t.Result FROM tests t INNER JOIN person P ON p.ID = t.PersonID ) T PIVOT ( sum(Result) FOR TestID IN ([1], [2], [3]) ) piv; </code></pre> <p>See <a href="http://www.sqlfiddle.com/#!3/bf74c/7" rel="nofollow">SQL Fiddle with Demo</a>.</p> <p>But if you have an unknown number of <code>TestId</code> values, then you will want to use dynamic SQL to generate the list of columns at run-time. You Code will be:</p> <pre><code>DECLARE @cols AS NVARCHAR(MAX), @colNames AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT distinct ',' + QUOTENAME(testId) from tests FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') select @colNames = STUFF((SELECT distinct ',' + QUOTENAME(testId) +' as Test'+cast(testId as varchar(10)) from tests FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT Name, age, ' + @colnames + ' from ( select P.Name, P.Age, t.TestID, t.Result from tests t inner join person P on p.ID = t.PersonID ) x pivot ( sum(Result) for TestID in (' + @cols + ') ) p ' execute(@query) </code></pre> <p>See <a href="http://www.sqlfiddle.com/#!3/bf74c/6" rel="nofollow">SQL Fiddle with Demo</a>.</p> <p>They both will generate the same result, difference being that the dynamic one will increase/decrease the columns if the number of test ids changes:</p> <pre><code>| NAME | AGE | TEST1 | TEST2 | TEST3 | -------------------------------------- | Jack | 25 | 125 | 120 | 75 | | Jill | 23 | 90 | 95 | 7.2 | </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
    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