关于表中行变列并且算和的问题?

Superisboy 2003-12-01 07:15:42

有table1,table2两个表
table1:
ID Name
1 name1
2 name2
3 name3
……
table2:
ID Name Num
10 name1 1
10 name2 1
10 name2 1
10 name3 1
……
生成table3或视图:
ID name1 name2 name3
10 1 2 1
……

做了一下午也没有做出来,请赐教,谢谢!
...全文
51 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2003-12-01
  • 打赏
  • 举报
回复
如果你table1中的数据固定,也可以直接用:

select id
,[name1]=sum(case name when 'name1' then num end)
,[name2]=sum(case name when 'name2' then num end)
,[name3]=sum(case name when 'name3' then num end)
from table2 group by id
zjcxc 元老 2003-12-01
  • 打赏
  • 举报
回复
--下面是数据测试

--创建测试表
create table table1(id int,name varchar(10))
insert into table1
select 1,'name1'
union all select 2,'name2'
union all select 3,'name3'

create table table2(ID int,Name varchar(10),Num int)
insert into table2
select 10,'name1',1
union all select 10,'name2',1
union all select 10,'name2',1
union all select 10,'name3',1

--查询处理
declare @s varchar(8000)
set @s=''
select @s=@s+',['+name+']=sum(case name when '''
+name+''' then num end)'
from table1
exec('select id'+@s+' from table2 group by id')

go
--删除测试环境
drop table table1,table2

/*--测试结果

id name1 name2 name3
----------- ----------- ----------- -----------
10 1 2 1

--*/
zjcxc 元老 2003-12-01
  • 打赏
  • 举报
回复
declare @s varchar(8000)
set @s=''
select @s=@s+',['+name+']=sum(case name when '''
+name+''' then num end)'
from table1
exec('select id'+@s+' from table2 group by id')


youngby 2003-12-01
  • 打赏
  • 举报
回复
mark
txlicenhe 2003-12-01
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/2440/2440306.xml?temp=.6941645
[交流]行列转换

34,874

社区成员

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

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