sql高手请进 ~~~ 看能否实现?

来源:百度知道 编辑:UC知道 时间:2024/05/13 05:18:23
例如:
year month value
2009 1 1.1
2009 2 1.2
2009 3 1.3
2010 1 2.1
2010 2 2.2
2010 3 2.3

想用sql语句实现以下效果:
year month1 month2 month3
2009 1.1 1.2 1.3
20010 2.1 2.2 2.3

能否实现?

这个问题是涉及行列转换问题
select year as year ,
max(case month when 1 then value else 0 end) month1,
max(case month when 2 then value else 0 end) month2,
max(case month when 3 then value else 0 end) month3
from table_1
group by year

select year,sum(a) month1,sum(b) month2,sum(c) month3
from
(select year ,value a,0 b,0 c
from table_name
where month=1
union all
select year ,0 a,value b,0 c
from table_name
where month=2
union all
select year ,0 a,0 b,value c
from table_name
where month=3)

可以实现。但是已经不属于查询了。只是人为的强行建表。

ACCESS数据库有一个这样的查询功能(交叉查询), 关键词是TRANSFORM的, SQL SERVER有没有就不知道了

学习, yaj52125 棒。