首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请问行转列

2012-12-15 
请教行转列ymrm201031201052201114201125201133结果m20102011104205313520m即月份,y即年请大家帮个忙,谢谢

请教行转列
y        m        rm
201031
201052
201114
201125
201133

结果
m    2010   2011
1    0      4
2    0      5
3    1      3
5    2      0

m即月份,y即年
请大家帮个忙,谢谢!
[最优解释]

create table tb(rm int,m int,y int)

insert tb
select 1,3,2010
union all
select 2,5,2010
union all
select 4,1,2011
union all
select 5,2,2011
union all
select 3,3,2011
drop table tb
declare @str varchar(1000)
set @str=''
select @str=@str+','+'max(case when y='+RTRIM(y)+' then rm else 0 end)['+RTRIM(y)+']' from tb group by y
set @str='select number+1 as m '+@str+' from master..spt_values a left join tb b on a.number+1=b.m 
     where type=''p'' and number<12 group by number+1'

exec(@str)
/*
m           2010        2011
----------- ----------- -----------
1           0           4
2           0           5
3           1           3
4           0           0
5           2           0
6           0           0
7           0           0
8           0           0
9           0           0
10          0           0
11          0           0
12          0           0

[其他解释]

create table tb(rm varchar(50),m varchar(50),year varchar(50))

insert tb
select '1','3','2010'
union all
select '2','5','2010'
union all
select '4','1','2011'
union all
select '5','2','2011'
union all
select '3','3','2011'


declare @sql varchar(max)
set @sql ='select m'
select @sql=@sql+', max(case year when '''+year+''' then rm else ''0'' end)['+year+']' from(select distinct year from tb)u


set @sql=@sql+'from tb group by m'
exec(@sql)


[其他解释]
y即年份,是动态的哦,可能是2009 2010 2011等
谢谢!
[其他解释]
select m,max(case when y=2010 then rm else 0 end) [2010],
max(case when y=2011 then rm else 0 end) [2010]
from tb group by m

[其他解释]
谢谢,我知道做了,估计是好久没做统计的缘故。晕
[其他解释]
declare @str varchar(1000)
set @str=''
select @str=@str+','+'max(case when y='+RTRIM(y)+' then rm else 0 end)'+RTRIM(y) from tb group by y
set @str='select m,'+@str+' from tb group by m'
exec(@str)

[其他解释]
Ver.2005,2008,2008R2
Create Table #
(
yint,
mint,
rmint
)

Insert # Select 2010,3,1
union Select 2010,5,2
union Select 2011,1,4
union Select 2011,2,5
union Select 2011,3,3

Select * From #

Select m,ISNULL([2010],0) As [2010],ISNULL([2011],0) As [2011] From # 
pivot(Sum(rm) for y in ([2010],[2011])) t

[其他解释]
引用:
SQL code
declare @str varchar(1000)
set @str=''
select @str=@str+','+'max(case when y='+RTRIM(y)+' then rm else 0 end)'+RTRIM(y) from tb group by y
set @str='select m,'+@str+' from tb group by m'
……


谢谢你的回答
能不能把缺少的月份也给补充进来呢。即
m 2010 2011
1 0 4
2 0 5
3 1 3
4 0 0
5 2 0
6 0 0
7 0 0
8 0 0
9 0 0
10 0 0
11 0 0
12 0 0

谢谢~~
[其他解释]
需要构造时间表
用MASTER..SPT_VALUES

热点排行
Bad Request.