Sql server 如何将中的行-列值转换为列值
如何将行-列值转换为列值 例如:- 我有5行,每行有5列。我需要根据ID进行转换 我的问题是:Sql server 如何将中的行-列值转换为列值,sql-server,Sql Server,如何将行-列值转换为列值 例如:- 我有5行,每行有5列。我需要根据ID进行转换 我的问题是: Select id,year,height,weight,date from user_det --------------------------------------------------------- | Id | Year | height| weight| date | ------------------------------------
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| | | |
您可以使用透视或条件聚合来实现这一点。但是,轴需要一个列:
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;
您可以使用透视或条件聚合来实现这一点。但是,轴需要一个列:
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;