合併有資料的列

2021-08-22 01:22:57 字數 2208 閱讀 2887

bom資料排序及分級顯示

--示例資料:

createtablet1(

namevarchar(20),

col1varchar(2),

col2varchar(2),

col3varchar(2))

insertt1(name,col1,col2,col3)

select'a','1','',''unionall

select'a','2','',''unionall

select'a','3','',''unionall

select'a','','4',''unionall

select'a','','5',''unionall

select'a','','6',''unionall

select'a','','7',''unionall

select'a','','','8'unionall

select'a','','','9'unionall

select'a','','','0'unionall

select'b','11','',''unionall

select'b','12','',''unionall

select'b','13','',''unionall

select'b','14','',''unionall

select'b','','15',''unionall

select'b','','16',''unionall

select'b','','17',''unionall

select'b','','','18'unionall

select'b','','','19'unionall

select'b','','','10'

go問題描述:

表t1中的列數不定,固定有乙個name列,大於1個的coln列,列名為col1~coln,要求根據name分組,合併各coln列中有值的資料。對於示例資料,要求結果如下:

namecol1col2col3

---------- --------------------------

a 1 4 0

a 258

a 369

a 7b1115 10

b 121618

b 131719

b14(所影響的行數為8行)

--處理**

declare@svarchar(8000),@iint,@fdvarchar(8000),@namevarchar(8000)

select@s='',@i=97,@fd='',@name='a.name'

select@i=@i+1,

@s=@s+'

fulljoin(

selectname,'+quotename(name)+',

id=(selectcount(*)fromt1

wherename=a.name

and'+quotename(name)+'>''''

and'+quotename(name)+'<=a.'+quotename(name)+')

fromt1a

where'+quotename(name)+'>''''

)'+char(@i)+'ona.name='+char(@i)+'.nameanda.id='+char(@i)+'.id',

@fd=@fd+',

'+quotename(name)+'=isnull('+char(@i)+'.'+quotename(name)+','''')',

@name='isnull('+char(@i)+'.name,'+@name+')'

fromsyscolumns

whereid=object_id(n't1')

andname<>'col1'

andnamelike'col%'

exec('

selectname='+@name+',

col1=isnull(a.col1,'''')'+@fd+'

from(

selectname,col1,

id=(selectcount(*)fromt1

wherename=a.name

andcol1>''''

andcol1<=a.col1)

fromt1a

wherecol1>''''

)a'+@s)

go 原帖位址

合併有資料的列

bom資料排序及分級顯示 示例資料 create table t1 name varchar 20 col1 varchar 2 col2 varchar 2 col3 varchar 2 insert t1 name,col1,col2,col3 select a 1 union all sele...

合併有資料的列

bom資料排序及分級顯示 示例資料 create table t1 name varchar 20 col1 varchar 2 col2 varchar 2 col3 varchar 2 insert t1 name,col1,col2,col3 select a 1 union all sele...

合併有資料的列

bom資料排序及分級顯示 示例資料 create table t1 name varchar 20 col1 varchar 2 col2 varchar 2 col3 varchar 2 insert t1 name,col1,col2,col3 select a 1 union all sele...