1

I have a select statement which checks for a name and a score from two separated tables. After select operation, I want second scores to be in another column for the same name.

Consider Score 69 will be next to 64 in another column. How can I do that?

Name Score

John  64
Lisa  45
Jack  23
John  69

Requested:

Name Score Score2

John 64 69

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Dra7m
  • 15
  • 3

1 Answers1

0

For a dynamic number of result columns, you'll almost certainly need to resort to dynamic SQL. Here's a take on this adapted from Bluefeet's answer here

DECLARE 
  @cols AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(CAST(ScoreNum AS VARCHAR))
            FROM
            (
                SELECT Name, Score, ROW_NUMBER() OVER (Partition By Name ORDER BY Score ASC) AS ScoreNum
                FROM NameScore
            ) scores
            FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');

SET @query = 'SELECT Name, ' + @Cols
+ '
FROM
(
    SELECT Name, Score, ROW_NUMBER() OVER (Partition By Name ORDER BY Score ASC) AS ScoreNum
    FROM NameScore
) scores
PIVOT
(
    MIN(Score)
    FOR ScoreNum IN (' + @cols + ')
) AS p';
 execute(@query);

With a sample SqlFiddle here

Noted that we had to run the query twice - once to see how many columns to create, and then again for the actual Pivot. For large amounts of data, you could DRY this up into a #Temp table @TableVar.

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • When run the query above, the output is:06974840 100 NULL NULL NULL NULL NULL NULL NULL NULL NULL 98 NULL 93 NULL NULL 12876324 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 14218452 100 NULL NULL NULL NULL NULL NULL NULL 100 NULL 96 NULL 90 NULL NULL 15133766 90 NULL NULL NULL NULL NULL 93 NULL 91 98 85 NULL 66 100 NULL 16278402 98 NULL NULL NULL NULL NULL 100 NULL 100 NULL 96 NULL 92 NULL NULL 19418462 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL – Dra7m Dec 09 '14 at 20:47
  • You've seen the fiddle? Obviously unpopulated cells in the pivot will be null - only the 'widest' person will have all column values. – StuartLC Dec 09 '14 at 20:50
  • I will check and let you know the result, thank you. – Dra7m Dec 09 '14 at 21:17