+ -
当前位置:首页 → 问答吧 → SQL 动态行转列

SQL 动态行转列

时间:2011-11-28

来源:互联网

现有的数据如下:
id a b
763219 3242 200611
763219 81 201006
7324123 13223 201103
7324123 2438903 201905
7324123 2345245 201002
435324523 1312 201703
同一id按照b列的大小排序后,同一个id补全7列数据。没有的数据可以是null也可以是0.

跪求.......
帮忙。。。help......
答对者送上香吻一个
想到达到的效果是:

id a_1 b_1 a_2 b_2 a_3 b_3
763219 3242 200611 81 201006 0 0  
7324123 2345245 201002 13223 201103 2438903 201905
435324523 1312 201703 0 0 0 0

作者: wlxshelley   发布时间: 2011-11-28

香吻 是什么东东?

作者: qianjin036a   发布时间: 2011-11-28

引用 1 楼 qianjin036a 的回复:
香吻 是什么东东?

作者: ssp2009   发布时间: 2011-11-28

wlx shelley
王凌雪? 吴乐萱?

作者: fcuandy   发布时间: 2011-11-28

SQL code
create table tb(id int,a int,b int)
insert into tb select 763219,3242,200611
insert into tb select 763219,81,201006
insert into tb select 7324123,13223,201103
insert into tb select 7324123,2438903,201905
insert into tb select 7324123,2345245,201002
insert into tb select 435324523,1312,201703
go
select id,
max(case when rn=1 then a else 0 end)a1,
max(case when rn=1 then b else 0 end)b1,
max(case when rn=2 then a else 0 end)a2,
max(case when rn=2 then b else 0 end)b2,
max(case when rn=3 then a else 0 end)a3,
max(case when rn=3 then b else 0 end)b3
from(
select row_number()over(partition by id order by (select 1))rn,* from tb
)t group by id
/*
id          a1          b1          a2          b2          a3          b3
----------- ----------- ----------- ----------- ----------- ----------- -----------
763219      3242        200611      81          201006      0           0
7324123     13223       201103      2438903     201905      2345245     201002
435324523   1312        201703      0           0           0           0

(3 行受影响)

*/
go
drop table tb

作者: qianjin036a   发布时间: 2011-11-28

楼上的得碗一个

作者: happyflystone   发布时间: 2011-11-28

引用 4 楼 qianjin036a 的回复:
SQL code
create table tb(id int,a int,b int)
insert into tb select 763219,3242,200611
insert into tb select 763219,81,201006
insert into tb select 7324123,13223,201103
insert into tb select 73241……

把你的香吻献给晴天大大。

作者: fredrickhu   发布时间: 2011-11-28