2014-12-03 91 views
-1

我已經從一個表中的以下樣品SQL移調行

+-------------+---+------------------+--+ 
| 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了它,並與這一個:)

EDIT失去意志:我沒有提到的事實是什麼成爲列在這個CAS動態即e d,e,s可以是任何東西,真的很感謝答案。

感謝所有

回答

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

什麼你正在尋找被稱爲PIVOT。它允許您將行轉換爲列。

-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 
+0

爲什麼downvote查詢時,不正是需要什麼? – CrimsonKing 2014-12-03 19:17:27