经过 @杨叔 和 @只羡鸳鸯不羡仙 的帮忙,我终于解决啦此问题,特贴代码于此。
-----------------------------------------------------
-----------------------------------------------------
原题:怎么把这样一个表儿(使用T-SQL语句)
years months amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成这样一个结果:
years m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
-----------------------------------------------------
-----------------------------------------------------
代码:
drop table testqq
create table testqq(years int, months int, amount float)
-----------------------------------------------------
-----------------------------------------------------
原题:怎么把这样一个表儿(使用T-SQL语句)
years months amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成这样一个结果:
years m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
-----------------------------------------------------
-----------------------------------------------------
代码:
drop table testqq
create table testqq(years int, months int, amount float)
insert into testqq values (1991,1,1.1)
insert into testqq values (1991,2,1.2)
insert into testqq values (1991,3,1.3)
insert into testqq values (1991,4,1.4)
insert into testqq values (1992,1,2.1)
insert into testqq values (1992,2,2.2)
insert into testqq values (1992,3,2.3)
insert into testqq values (1992,4,2.4)
insert into testqq values (1991,2,1.2)
insert into testqq values (1991,3,1.3)
insert into testqq values (1991,4,1.4)
insert into testqq values (1992,1,2.1)
insert into testqq values (1992,2,2.2)
insert into testqq values (1992,3,2.3)
insert into testqq values (1992,4,2.4)
select * from testqq
select years,
sum(case when a.months=1 then amount end) as month1,
sum(case when a.months=2 then amount end) as month2,
sum(case when a.months=3 then amount end) as month3,
sum(case when a.months=4 then amount end) as month4
from testqq a group by years
sum(case when a.months=1 then amount end) as month1,
sum(case when a.months=2 then amount end) as month2,
sum(case when a.months=3 then amount end) as month3,
sum(case when a.months=4 then amount end) as month4
from testqq a group by years