SQL将行转置为列

时间:2014-12-03 17:37:25

标签: sql-server pivot

我从表格中得到以下样本

+-------------+---+------------------+--+
| Heading1    | 2  | 3               |  |
+-------------+---+------------------+--+
| Cats        | d | 1                |  |
| Cats        | e | 13/01/2000 12:29 |  |
| Dogs        | s | 1                |  |
| Dogs        | e | 13/01/2000 12:29 |  |
| Frogs       | d | 1                |  |
| Frogs       | e | 13/01/2000 12:29 |  |
| Cows        | d | 1                |  |
| Cows        | e | 13/01/2000 12:29 |  |
+-------------+---+------------------+--+

我希望第2列的行是不同的标题,并为1和3 a中的每个唯一值包含一行,如下所示:

+-----------+------+------------------+------+
| Headings: |  d   |        e         |  s   |
+-----------+------+------------------+------+
| Cats      | 1    | 13/01/2000 12:29 | Null |
| Dogs      | Null | 13/01/2000 12:29 | 1    |
| Frogs     | 1    | 13/01/2000 12:29 | Null |
| Cows      | 1    | 13/01/2000 12:29 | Null |
+-----------+------+------------------+------+

任何想法都用Google搜索并失去了意志:)

编辑:我没有提到的是,成为列的内容是动态的,即在这种情况下d,e,s并且可以是任何内容,非常感谢答案。

全部谢谢

3 个答案:

答案 0 :(得分:1)

您可以通过两种方式转置rows to columns

方法1: Conditional Aggregate

<强> SQL FIDDLE DEMO

SELECT Heading1,
       Max(CASE WHEN [2] = 'd' THEN [3] END) 'd',
       Max(CASE WHEN [2] = 'e' THEN [3] END) 'e',
       Max(CASE WHEN [2] = 's' THEN [3] END) 's'
FROM   <tablename>
GROUP  BY Heading1

方法2: Pivot

<强> SQL FIDDLE DEMO

SELECT *
FROM  (SELECT *
       FROM   <tablename>) a
      PIVOT (Max([3])
            FOR [2] IN ([d],
                        [e],
                        [s])) piv 

答案 1 :(得分:-1)

您正在寻找的内容称为PIVOT。它允许您将行转换为列。

答案 2 :(得分:-1)

SELECT Heading1,
  (SELECT Heading3 FROM Table2 b WHERE a.Heading1 = b.Heading1 and b.Heading2 = 'd') as d,
  (SELECT Heading3 FROM Table2 b WHERE a.Heading1 = b.Heading1 and b.Heading2 = 'e') as e,
  (SELECT Heading3 FROM Table2 b WHERE a.Heading1 = b.Heading1 and b.Heading2 = 's') as s
INTO Table2
FROM Table1 a
GROUP BY Heading1