如何将行列值转换为列值

时间:2017-02-08 04:20:48

标签: sql-server

我们如何将行列值转换为列值。

例如: -

我有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|          |         |       | 

1 个答案:

答案 0 :(得分: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;