sql中如何将某列的行内容变成列字段名?真诚感谢!

hzliuhai88 2009-02-12 12:18:16
sql如何表中将某列的行内容变成列字段名(注:些表内容为动态)?如:
金额 日期 名称
100 200802 abc
85 200802 def
150 200812 abc
0 200812 def

现要实现如下:
名称 200802 200812
abc 100 150
def 150 0
...全文
1260 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2009-02-12
  • 打赏
  • 举报
回复
[Quote=引用楼主 hzliuhai88 的帖子:]
sql如何表中将某列的行内容变成列字段名(注:些表内容为动态)?如:
金额 日期 名称
100 200802 abc
85 200802 def
150 200812 abc
0 200812 def

现要实现如下:
名称 200802 200812
abc 100 150
def 150 0
[/Quote]
行列转换.

create table tb(金额 INT, 日期 varchar(10), 名称 varchar(10))
insert into tb values(100 , '200802' , 'abc')
insert into tb values(85 , '200802' , 'def')
insert into tb values(150 , '200812' , 'abc')
insert into tb values(0 , '200812' , 'def')
go

select 名称,
sum(case 日期 when '200802' then 金额 else 0 end) '200802',
sum(case 日期 when '200812' then 金额 else 0 end) '200812'
from tb
group by 名称

drop table tb
/*
名称 200802 200812
---------- ----------- -----------
abc 100 150
def 85 0

(所影响的行数为 2 行)
*/
chuifengde 2009-02-12
  • 打赏
  • 举报
回复 1
declare @a varchar(1000)
select @sql=isnull(@sql+',','')+' max(case when 日期='''+日期+''' then 金额 else 0 end)['+日期+']' from 表 group by 日期

exec('select 名称,'+@sql+' from 表 group by 名称')
子陌红尘 2009-02-12
  • 打赏
  • 举报
回复

declare @sql varchar(8000)
set @sql=''

select @sql=@sql+',['+rtrim(日期)+']=sum(case 日期 when '''+日期+''' then 金额 else 0 end)' from (select distinct 日期 from 表) t

set @sql='select 名称'+@sql+' from 表 group by 名称'

exec(@sql)
微雨新晨 2021-07-05
  • 举报
回复
@子陌红尘 看不懂,可以解释下嘛
水族杰纶 2009-02-12
  • 打赏
  • 举报
回复
if object_id('tb')is not null drop table tb
go
create table tb(金额 money, 日期 varchar(10), 名称 varchar(10))
insert tb select 100 , '200802', 'abc'
insert tb select 85 , '200802' , 'def'
insert tb select 150, '200812' , 'abc'
insert tb select 0 , '200812' ,'def'
select 名称,sum(case when 日期='200802' then 金额 else 0 end)[200802],
sum(case when 日期='200812' then 金额 else 0 end)[200812] from tb group by 名称
/*名称 200802 200812
---------- --------------------- ---------------------
abc 100.0000 150.0000
def 85.0000 .0000*/
yun920920 2009-02-12
  • 打赏
  • 举报
回复
很好很强大,路过学的,多谢
hzliuhai88 2009-02-12
  • 打赏
  • 举报
回复
谢谢,chuifengde 楼友,真高人也。

22,209

社区成员

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

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