--示例数据:
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 ALLSELECT 'A','2','','' UNION ALLSELECT 'A','3','','' UNION ALLSELECT 'A','','4','' UNION ALLSELECT 'A','','5','' UNION ALLSELECT 'A','','6','' UNION ALLSELECT 'A','','7','' UNION ALLSELECT 'A','','','8' UNION ALLSELECT 'A','','','9' UNION ALLSELECT 'A','','','0' UNION ALLSELECT 'B','11','','' UNION ALLSELECT 'B','12','','' UNION ALLSELECT 'B','13','','' UNION ALLSELECT 'B','14','','' UNION ALLSELECT 'B','','15','' UNION ALLSELECT 'B','','16','' UNION ALLSELECT 'B','','17','' UNION ALLSELECT 'B','','','18' UNION ALLSELECT 'B','','','19' UNION ALLSELECT 'B','','','10' go
--问题描述:
表t1中的列数不定,固定有一个Name列,大于1个的Coln列,列名为Col1~Coln,要求根据Name分组,合并各Coln列中有值的数据。对于示例数据,要求结果如下:Name Col1 Col2 Col3 ---------- --------- --------- -------- A 1 4 0A 2 5 8A 3 6 9A 7 B 11 15 10B 12 16 18B 13 17 19B 14--邹建的sql2000下解决办法:
SELECT Name=ISNULL(c.Name,ISNULL(b.Name,a.name)),
Col1=ISNULL(A.Col1,''), [Col2]=ISNULL(b.[Col2],''), [Col3]=ISNULL(c.[Col3],'') 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 FULL JOIN (SELECT Name, [Col2], ID=(SELECT COUNT(*) FROM t1 WHERE Name=a.Name AND [Col2]>'' AND [Col2]<=a.[Col2]) FROM t1 a WHERE [Col2]>'')b ON a.Name=b.Name AND a.ID=b.ID FULL JOIN (SELECT Name, [Col3], ID=(SELECT COUNT(*) FROM t1 WHERE Name=a.Name AND [Col3]>'' AND [Col3]<=a.[Col3]) FROM t1 a WHERE [Col3]>'')c ON a.Name=c.Name AND a.ID=c.ID
--我在SQL2005下写的方法(这里用到了CTE):
with TT1 as
(select ROW_NUMBER() over (partition by Name order by Col1) as T,Name,Col1from t1 where Col1 <> ''),TT2 as(select ROW_NUMBER() over (partition by Name order by Col2) as T,Name,Col2from t1 where Col2 <> ''),TT3 as(select ROW_NUMBER() over (partition by Name order by Col3) as T,Name,Col3from t1 where Col3 <> '')select case when TT1.Name IS not null then TT1.name when TT2.Name is not null then TT2.name when TT3.Name is not null then TT3.name end as name, case when TT1.Col1 IS NULL then '' else TT1.Col1 end as Col1, case when TT2.Col2 IS NULL then '' else TT2.Col2 end as Col2, case when TT3.Col3 IS NULL then '' else TT3.Col3 end as Col3from TT1 full join TT2 on TT1.T = TT2.T and TT1.Name = TT2.Namefull join TT3 on TT1.T = TT3.T and TT1.Name=TT3.Name