求一条sql语句。。。

quou2002 2006-08-02 10:34:52
现有一个表,结构及数据如下:
id money type (无主键,无重复行)
1 111 a
1 222 b
1 333 c
欲实现如下效果,sql怎么写?
id a b c
1 111 222 333
先暂时只考虑type就只有a,b,c 三种类型;
当type存在多种类型时,例如还有一类d,那么我想实现结果集(id,a,b,c,d),该怎么做?
...全文
190 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
liangpei2008 2006-08-02
  • 打赏
  • 举报
回复
行转列................
hellowork 2006-08-02
  • 打赏
  • 举报
回复
if object_id('tb') is not null
drop table tb
go
create table tb(id int,money int,type varchar(10))
insert tb
select 1,111,'a' union all
select 1,222,'b' union all
select 1,333,'c'

----静态写法
select id,
a=sum(case type when 'a' then money else 0 end),
b=sum(case type when 'b' then money else 0 end),
c=sum(case type when 'c' then money else 0 end)
from tb group by id

----动态写法(适合"当type存在多种类型时,例如还有一类d,那么我想实现结果集(id,a,b,c,d),该怎么做?")
declare @str varchar(2000)
set @str = ''
select @str = @str + ',' + type + '=sum(case type when ''' + type + ''' then money else 0 end)'
from (select distinct type from tb) a /*去掉重复的type*/
--print @str

----执行汇总
exec ('select id '+ @str + ' from tb group by id')

----清除测试环境
drop table tb
xyxfly 2006-08-02
  • 打赏
  • 举报
回复
http://www.52sdn.com/artid/195/195875.html

http://www.cnblogs.com/acelove/archive/2004/11/29/70434.aspx

我就不写了,机器挂了,用别人机器,没装SQL,郁闷啊......
xyxfly 2006-08-02
  • 打赏
  • 举报
回复
楼主搜索一下行转列,很多这样的例子
lanchong 2006-08-02
  • 打赏
  • 举报
回复
占座学习,另外如果ID不唯一的时候应该怎么做,非常想知道

34,588

社区成员

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

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