将列值设为标题

时间:2014-08-13 18:30:18

标签: sql sql-server-2008 pivot

请帮助我,因为我还是新用SQL Server。我有下表

  Order  |  SCHGP  |      Item       |
+--------+---------+-----------------+
| 220132 | Class 1 | 0121R00007PDG   |
| 220132 | Class 2 | 0201R00046      |
| 220132 | Class 3 | 4400464PLGB     |
| 220132 | Class 4 | 4400466PLGB     |
|        | Class 5 | 4400468PLG      |
| 220132 | Class 6 | 0121R00013PDG   |
| 220167 | Class 1 | 0121R00006PNG   |
| 220167 | Class 2 | 0201R00338      |
| 220167 | Class 3 | 0121R00344PNG   |
| 220167 | Class 4 | 0121R00352PNG   |
| 220167 | Class 5 | 0121R00010PNG   |
+--------+---------+-----------------+

并希望得到以下内容(基本上按订单分组并将SCHGP列放入标题中):

║  Order ║    Class 1    ║  Class 2   ║    Class 3    ║    Class 4    ║    Class 5    ║    Class 6    ║
╠════════╬═══════════════╬════════════╬═══════════════╬═══════════════╬═══════════════╬═══════════════╣
║ 220132 ║ 0121R00007PDG ║ 0201R00046 ║ 4400464PLGB   ║ 4400466PLGB   ║ 4400468PLG    ║ 0121R00013PDG ║
║ 220167 ║ 0121R00006PNG ║ 0201R00338 ║ 0121R00344PNG ║ 0121R00352PNG ║ 0121R00010PNG ║               ║
╚════════╩═══════════════╩════════════╩═══════════════╩═══════════════╩═══════════════╩══════════════

任何提示都将不胜感激!

1 个答案:

答案 0 :(得分:1)

根据您的示例数据和结果,这里是SQL Server中的PIVOT

<强> SQL Fiddle Demo

SELECT * 
FROM   
  (select [order], schgp, STUFF(
      (
        select cast(' ' as varchar(max)) + item
        from testpivot t1
        where t1.[order] = t2.[order] and t1.schgp = t2.schgp
        for xml path('')
      ), 1, 1, '') AS item
from testpivot t2
) a 
PIVOT 
  (Max(item) 
   FOR schgp IN ([Class 1], [Class 2], [Class 3], [Class 4], [Class 5], [Class 6])) AS pvt