sql统计问题

muzhenxing013 2008-08-04 02:23:49
我有这样一张表,比如说是
ID 姓名 钱
1 张三 10
2 李四 20
3 王麻子 30

想变成

id 张三 李四 王麻子
1 10 0 0
2 0 20 0
3 0 0 30

就是交叉报表,谢谢
...全文
70 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
muzhenxing013 2008-08-04
  • 打赏
  • 举报
回复
我有这样一张表,比如说是
ID 姓名 钱 学历
1 张三 10 a
2 李四 20 b
3 王麻子 30 才

想变成

id 张三 李四 王麻子
1 10 a 0 0 0 0
2 0 0 20 b 0 0
3 0 0 0 0 30 0

就是交叉报表,谢谢
谢谢,跪求
wgzaaa 2008-08-04
  • 打赏
  • 举报
回复
跟着老大接分
hery2002 2008-08-04
  • 打赏
  • 举报
回复
动态转换,
1楼 :)
-狙击手- 2008-08-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 libin_ftsafe 的回复:]
SQL codedeclare @str varchar(8000)
set @str='select id'

select @str=@str+',['+rtrim(姓名)+']=sum(case 姓名 when '''+姓名+''' then 钱 else 0 end)' from (select distinct 姓名 from 表) t

set @str=@str+' from 表 group by id'

exec(@sql)
[/Quote]
sdxiong 2008-08-04
  • 打赏
  • 举报
回复

怎么不搜一下呢??这论坛里相同问题的贴子有一大堆了
子陌红尘 2008-08-04
  • 打赏
  • 举报
回复
create table 表(id int,姓名 varchar(20),钱 int)
insert into 表 select 1,'张三',10
insert into 表 select 2,'李四',20
insert into 表 select 3,'王麻子',30
go

declare @str varchar(8000)
set @str='select id'

select @str=@str+',['+rtrim(姓名)+']=sum(case 姓名 when '''+姓名+''' then 钱 else 0 end)' from (select distinct 姓名 from 表) t

set @str=@str+' from 表 group by id'

exec(@str)
/*
id 李四 王麻子 张三
----------- ----------- ----------- -----------
1 0 0 10
2 20 0 0
3 0 30 0
*/
go

drop table 表
go
子陌红尘 2008-08-04
  • 打赏
  • 举报
回复
declare @str varchar(8000)
set @str='select id'

select @str=@str+',['+rtrim(姓名)+']=sum(case 姓名 when '''+姓名+''' then 钱 else 0 end)' from (select distinct 姓名 from 表) t

set @str=@str+' from 表 group by id'

exec(@sql)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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