求一SQL语句

michael_monkey 2013-05-17 11:57:41
表A:
A B F1 F2 F3
-------------------------------------
A1 B1 1 2 NULL
A1 B2 NULL 2 1
A2 B1 1 NULL NULL
A2 B2 NULL 1 1
通过SQL想要的结果:
A1 B1 F1
A1 B1 F2
A1 B2 F2
A1 B2 F3
A2 B1 F1
A2 B2 F2
A2 B2 F3

如果F1、F2、F3值大于0,则作为第三列与A和B列形成一条记录,并且值以列名称替代

需要动态的SQL,因为实际情况不止F1、F2、F3,而是F1到F131,100多列。
...全文
153 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
哥眼神纯洁不 2013-05-17
  • 打赏
  • 举报
回复

declare @sql varchar(max) =''
select @sql=@sql+'union all select a,b,'+''''+
name+''''+' from a where '+name+' is not null '  
from sys.columns where object_id in(
select object_id from sys.objects where name='a')
and name not in('a','b')
set @sql=SUBSTRING(@sql,10,len(@sql))+' order by 1,2,3'
exec( @sql)
524929657雯 2013-05-17
  • 打赏
  • 举报
回复
跟我这个差不多。 行转列问题 if not object_id('ClassDeng') is null drop table ClassDeng Go Create table ClassDeng([Student] nvarchar(2),[数学] int,[物理] int,[英语] int,[语文] int,[化学] int) Insert ClassDeng select N'李四',77,85,65,65,88 union all select N'张三',87,90,82,78,87 union all select N'麻子',67,64,77,89,58 Go --- student 数学 物理 英语 语文 化学 李四 77 85 65 65 88 张三 87 90 82 78 87 麻子 66 64 77 89 58 declare @s nvarchar(4000) select @s=isnull(@s+' union all ','')+'select [Student],[Course]='+quotename(Name,'''') +',[Score]='+quotename(Name)+' from ClassDeng'from syscolumns where ID=object_id('ClassDeng') and Name not in('Student') order by Colid exec('select * from ('+@s+')t order by [Student],[Course]') -----运行结果 student Course Score 李四 数学 77 李四 物理 85 李四 英语 65 李四 语文 65 李四 化学 88 张三 数学 87 张三 物理 90 张三 英语 82 张三 语文 78 张三 化学 87 麻子 数学 66 麻子 物理 64 麻子 英语 77 麻子 语文 89 麻子 化学 58 ==================== 希望能帮到你。
michael_monkey 2013-05-17
  • 打赏
  • 举报
回复
楼上的代码运行不起来,版本不一样?我是sqlserver2005,改了一下,可以了,谢谢。 declare @sql nvarchar(4000) set @sql='' select @sql=@sql+ 'union all select a,b,'+''''+ name+''''+' from a where '+name+' is not null ' from syscolumns where id in ( select id from sysobjects where name='a') and name not in('a','b') set @sql=SUBSTRING(@sql,10,len(@sql))+' order by 1,2,3' exec(@sql) 另外自己的笨办法: create table B (A nvarchar(50), B nvarchar(50), C nvarchar(50)) declare @i int declare @sqlstr nvarchar(1000) set @i=1 while @i<=3 begin set @sqlstr='Insert into B (A,B,C) select A,B,''F'+cast(@i as nvarchar)+''' from A where isnull(F'+cast(@i as nvarchar)+',0)>0' exec(@sqlstr) set @i=@i+1 end select * from B

34,838

社区成员

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

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