行列转换 急!

tl_pear 2009-04-07 10:26:32
Col1 Col2 Col3
2009年2月第一期 海宁旅行者 100
2009年2月第一期 湖州宝吉 92
2009年3月第一期 海宁旅行者 90
2009年3月第一期 湖州宝吉 80
2009年4月第一期 湖州宝吉 96

把上面的数据格式变成下面的格式,

Col1 海宁旅行者 湖州宝吉
2009年2月第一期 100 92
2009年3月第一期 90 80
2009年4月第一期 null 96

谢谢!

...全文
116 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
XavierRuan 2012-02-27
  • 打赏
  • 举报
回复

select * from s
pivot
(max(col3) for col2 in([海宁旅行者],[湖州宝吉]))b
yygyogfny 2009-04-07
  • 打赏
  • 举报
回复
declare @sql nvarchar(4000)
set @sql = ''

select @sql = @sql + 'max(case when col2=''' + col2 + ''' then col3 else 0 end )['+ col2+ '],' from tb group by col2

select @sql = 'select col1, ' + left(@sql,len(@sql)-1) + ' from tb group by col1 '

exec(@sql)

没调试~~~
lg3605119 2009-04-07
  • 打赏
  • 举报
回复
select col1,
sum(case when col2='海宁旅行者' then col3 else 0 end)[海宁旅行者],
sum(case when col2=' 湖州宝吉' then col3 else 0 end)[ 湖州宝吉]
from tb group by col1
pt1314917 2009-04-07
  • 打赏
  • 举报
回复

--哦,看错了。直接这样就可以了

declare @sql varchar(8000)
set @sql='select col1'
select @sql=@sql+',['+col2+']=sum(case col2 when '''+col2+''' then col3 else 0 end)'
from (select distinct col2 from s)a
set @sql=@sql+' from s group by col1'
exec(@sql)
pt1314917 2009-04-07
  • 打赏
  • 举报
回复
--> 测试数据: [s]
if object_id('[s]') is not null drop table [s]
create table [s] (Col1 varchar(15),Col2 varchar(10),Col3 int)
insert into [s]
select '2009年2月第一期','海宁旅行者',100 union all
select '2009年2月第一期','湖州宝吉',92 union all
select '2009年3月第一期','海宁旅行者',90 union all
select '2009年3月第一期','湖州宝吉',80 union all
select '2009年4月第一期','湖州宝吉',96
go

declare @sql varchar(8000)
set @sql='select col1=left(col1,7)'
select @sql=@sql+',['+col2+']=sum(case col2 when '''+col2+''' then col3 else 0 end)'
from (select distinct col2 from s)a
set @sql=@sql+' from s group by left(col1,7)'
exec(@sql)

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧