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
select 'a','2','','' union all
select 'a','3','','' union all
select 'a','','4','' union all
select 'a','','5','' union all
select 'a','','6','' union all
select 'a','','7','' union all
select 'a','','','8' union all
select 'a','','','9' union all
select 'a','','','0' union all
select 'b','11','','' union all
select 'b','12','','' union all
select 'b','13','','' union all
select 'b','14','','' union all
select 'b','','15','' union all
select 'b','','16','' union all
select 'b','','17','' union all
select 'b','','','18' union all
select 'b','','','19' union all
select 'b','','','10'
go問題描述:
表t1中的列數不定,固定有乙個name列,大於1個的coln列,列名為col1~coln,要求根據name分組,合併各coln列中有值的資料。對於示例資料,要求結果如下:
name col1 col2 col3
---------- --------- --------- --------
a 1 4 0
a 2 5 8
a 3 6 9
a 7
b 11 15 10
b 12 16 18
b 13 17 19
b 14
(所影響的行數為 8 行)
--處理**
declare @s varchar(8000),@i int,@fd varchar(8000),@name varchar(8000)
select @s='',@i=97,@fd='',@name='a.name'
select @i=@i+1,
@s=@s+'
full join(
select name,'+quotename(name)+',
id=(select count(*) from t1
where name=a.name
and '+quotename(name)+'>''''
and '+quotename(name)+'<=a.'+quotename(name)+')
from t1 a
where '+quotename(name)+'>''''
)'+char(@i)+' on a.name='+char(@i)+'.name and a.id='+char(@i)+'.id',
@fd=@fd+',
'+quotename(name)+'=isnull('+char(@i)+'.'+quotename(name)+','''')',
@name='isnull('+char(@i)+'.name,'+@name+')'
from syscolumns
where id=object_id(n't1')
and name<>'col1'
and name like 'col%'
exec('
select name='+@name+',
col1=isnull(a.col1,'''')'+@fd+'
from(
select name,col1,
id=(select count(*) from t1
where name=a.name
and col1>''''
and col1<=a.col1)
from t1 a
where col1>''''
)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資料排序及分級顯示 示例資料 createtablet1 namevarchar 20 col1varchar 2 col2varchar 2 col3varchar 2 insertt1 name,col1,col2,col3 select a 1 unionall select a 2 u...