2017-02-08 61 views
1

如何將行列值轉換爲列值。如何將行列值轉換爲列值

例如: -

我有5行,每行有5列。我需要根據ID進行轉換。

我的查詢是:

Select id,year,height,weight,date from user_det 

--------------------------------------------------------- 
| Id | Year  | height| weight|  date  | 
--------------------------------------------------------- 
| 1 | 20082009 | 122 | 23 |  4/15/2009 | 
--------------------------------------------------------- 
| 1 | 20092010 | 135 | 39 |  3/19/2010 | 
--------------------------------------------------------- 
| 2 | 20082009 | 132 | 20 |  2/23/2009 | 
--------------------------------------------------------- 
| 3 | 20142015 | 133 | 28 |  2/24/2015 | 
--------------------------------------------------------- 

如果我按ID最多2我需要結果像下表

id | year1 | height1 |weight1 | date1 | year2 | height2|weight2|date2 
------------------------------------------------------------------------------- 
1 |20082009| 122 | 23 |4/15/2009| 20092010 | 135  | 39 |3/19/2010 
-------------------------------------------------------------------------------- 
2 |20082009 | 135  | 20 |2/23/2009|   |   |  | 
-------------------------------------------------------------------------------- 
3 |20152015 | 133  | 28 |2/24/2015|   |   |  | 

回答

4

您可以旋轉或者有條件的聚集做到這一點。但是,你需要一個關鍵的專欄:

select id, 
     max(case when seqnum = 1 then year end) as year_1, 
     max(case when seqnum = 1 then height end) as height_1, 
     max(case when seqnum = 1 then weight end) as weight_1, 
     max(case when seqnum = 1 then date end) as date_1, 
     max(case when seqnum = 2 then year end) as year_2, 
     max(case when seqnum = 2 then height end) as height_2, 
     max(case when seqnum = 2 then weight end) as weight_2, 
     max(case when seqnum = 2 then date end) as date_2 
from (select t.*, 
      row_number() over (partition by id order by year) as seqnum 
     from user_det t 
    ) t 
group by id; 
+0

謝謝你這麼多..工作很好.. – Asm1990