透视具有多个值的列

时间:2016-10-20 06:22:54

标签: sql sql-server pivot

表#Temp:

ID    Name        Hobbies
1     xxx          Reading
1     xxx          Sports
1     xxx          Dance
2     xyz          Dance
3     yyy          Swimming
3     yyy          Reading

现在,我希望结果集为:

ID   Name    Hobby1     Hobby2    Hobby3 
1    xxx     Reading    Sports    Dance         
2    xyz     Cooking                  
3    yyy     Coloring   Swimming        

如何做到这一点?我已经使用了多个爱好值,所以我不能硬编码。

3 个答案:

答案 0 :(得分:3)

由于您知道每个名称的最大爱好数量您可以为每个名称生成行号并将其用于旋转

;with data as
(
SELECT row_number()over(partition by [ID] order by [Hobbies])rn,*
FROM   ( VALUES (1,'xxx','Reading'),
                (1,'xxx','Sports'),
                (1,'xxx','Dance'),
                (2,'xyz','Dance'),
                (3,'yyy','Swimming'),
                (3,'yyy','Reading')) tc ([ID], [Name], [Hobbies])
)
SELECT [ID],
       [Name],
       [Hobby1] = Max(CASE WHEN rn = 1 THEN [Hobbies] END),
       [Hobby2] = Max(CASE WHEN rn = 2 THEN [Hobbies] END),
       [Hobby3] = Max(CASE WHEN rn = 3 THEN [Hobbies] END)
FROM   data
GROUP  BY [ID],
          [Name] 

结果:

╔════╦══════╦═════════╦══════════╦════════╗
║ ID ║ Name ║ Hobby1  ║  Hobby2  ║ Hobby3 ║
╠════╬══════╬═════════╬══════════╬════════╣
║  1 ║ xxx  ║ Dance   ║ Reading  ║ Sports ║
║  2 ║ xyz  ║ Dance   ║ NULL     ║ NULL   ║
║  3 ║ yyy  ║ Reading ║ Swimming ║ NULL   ║
╚════╩══════╩═════════╩══════════╩════════╝

答案 1 :(得分:1)

尝试这样

DECLARE @tbl TABLE(ID INT,Name VARCHAR(100),Hobbies VARCHAR(100));
INSERT INTO @tbl VALUES
 (1,'xxx','Reading')
,(1,'xxx','Sports')
,(1,'xxx','Dance')
,(2,'xyz','Dance')
,(3,'yyy','Swimming')
,(3,'yyy','Reading');

SELECT p.*
FROM
(
    SELECT tbl.*
          ,'Hobby' + CAST(ROW_NUMBER() OVER(PARTITION BY tbl.Name ORDER BY tbl.ID) AS VARCHAR(10)) AS ColumnName
    FROM @tbl AS tbl
) AS t
PIVOT
(
    MAX(Hobbies) FOR ColumnName IN(Hobby1,Hobby2,Hobby3,Hobby4 /*add more if needed*/)
) AS p

结果

ID  Name    Hobby1   Hobby2  Hobby3 Hobby4
1   xxx     Reading  Sports   Dance NULL
2   xyz     Dance    NULL     NULL  NULL
3   yyy     Swimming Reading  NULL  NULL

答案 2 :(得分:1)

试试这个......

<input type="text" id="43" name="textbox1">
<input type="text" id="85" name="textbox2">
<input type="text" id="10" name="textbox3">
<input type="text" id="25" name="textbox4">
<input type="text" id="99" name="textbox5">
<script>
  document.getElementById("10")
  .insertAdjacentHTML("afterend"
  , "<input type=text id=123 name=textbox3-5 value=3.5>");
</script>