0

Hi I have the following table that I would like to use the pivot function on:

Id|Number| Code
1 |  34  |abc12345
1 |  23  |xqwe6758
2 |  37  |ghut564hg
3 | 456  |ghut8695
3 |  39  |ghtuj678
3 |  22  |fsdifje12

And I want it to be displayed horizontally as the following:

Id| Code1    | Code2    | Code3
1 | abc12345 | xqwe6758 | null  
2 |ghut564hg | null     | null
3 |ghut8695  | ghtuj678 | fsdifje12


SELECT Id
      ,[Code1]
      ,[Code2]
      ,[Code3]
  FROM(SELECT Id,Code
        FROM [TableName] 
  )d
  pivot(
  max(Id)
  for Code in([Code1],[Code2],[Code3])
  )as piv;

This throws an invalid column name error on the Id column. Could someone help identify the error ?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
user7221204
  • 99
  • 3
  • 12

2 Answers2

2

You can use pivot as below:

;with cte as 
(
    select  
        id, code, 
        RowN = Row_Number() over (partition by id order by code) 
    from 
        yourtable1
) 
select * 
from cte
pivot ( max(code) for RowN in([1], [2], [3])) p

For varying columns you can use stuff to create columns list and then use dynamic SQL to run with varying columns... But it is available in various examples in SO itself...

Added my output:

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38
1

Try this

DECLARE @tbl TABLE(Id INT, Code VARCHAR(100));
INSERT INTO @tbl VALUES
 (1,'abc12345')
,(1,'xqwe6758')
,(2,'ghut564hg')
,(3,'ghut8695')
,(3,'ghtuj678')
,(3,'fsdifje12');

SELECT p.*
FROM
(
    SELECT Id
           ,'Code' + CAST(ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Code) AS VARCHAR(10)) AS ColumnName
           ,Code
    FROM @tbl
) AS t
PIVOT
(
    MAX(Code) FOR ColumnName IN(Code1,Code2,Code3 /*add as many as you need*/)
) AS p

The result

Id  Code1       Code2       Code3
1   abc12345    xqwe6758    NULL
2   ghut564hg   NULL        NULL
3   fsdifje12   ghtuj678    ghut8695
Shnugo
  • 66,100
  • 9
  • 53
  • 114