今天在CSDN上看见有人提出如下的SQL统计问题,于是帮他写了一个SQL语句。
问题如下:
表结构如下
要实现的效果如下:
这个涉及行专列问题,SQL语句如下:
insert into product values('13303','茶杯','蓝色','a',20); insert into product values('13303','茶杯','蓝色','b',10); insert into product values('13303','茶杯','蓝色','c',30); insert into product values('13303','茶杯','灰色','a',10); insert into product values('13304','水杯','白色','b',20); declare @sql varchar(8000) set @sql = 'select [id],[name],[color] ' select @sql = @sql + ' , max(case [size] when ''' + [size] + ''' then number else 0 end) [' + [size] + ']' from (select distinct [size] from product) as a set @sql = @sql + ' from product group by [id],[name],[color]' exec(@sql)
最终显示效果如下图:
SQL行列转换+合并操作,原帖地址:http://bbs.csdn.net/topics/390348963
Create table 数据 --创建表 ( ID Int IDENTITY(1,1) not null, 编号 Varchar(50), 明细 Varchar(50), Primary Key(ID) ); Insert Into 数据 Select 1,'a' Union all Select 1,'b' Union all Select 1,'c' Union all Select 2,'a' Union all Select 2,'b' Union all Select 2,'d'Union all Select 3,'a'Union all Select 3,'b' --创建自定义函数 Create Function CSDN ( @mx Varchar(50) ) Returns Varchar(8000) as Begin Declare @str Varchar(8000) Set @str = '' Select @str = @str + cast(明细 as Varchar(50)) + ',' from 数据 Where 编号 = @mx Set @str = SubString(@str,1,len(@str)-1) Return(@str) End --调用自定义函数得到结果 Select Distinct 编号,dbo.CSDN(编号) as 明细From 数据;