在数据表test中存在如下数据
sno snum ssex sremark
a 1 m xx
a 2 fm xxx
a 3 fm xxxxx
b 2 fm x
b 3 m xxxx
b 4 fm xx
c 8 m xxx
c 9 fm xxxx
要提取的数据为
a 1 xx xxx xxxxx
b 2 x xxxx xx
c 8 xxx xxxx
具体描述为:根据sno将数据分组,再提取每个分组的最小snum,再将每个分组的sremark用两个空格隔开提取成一个字符串
要求:不能使用 游标 等效率比较低的方法,因为有可能test表有十万以上的数据
期待各位的精彩回答
------解决思路----------------------
with test(sno,snum,ssex,sremark) as
(
select 'a',1,'m','xx' union all
select 'a',2,'fm','xxx' union all
select 'a',3,'fm','xxxxx' union all
select 'b',2,'fm','x' union all
select 'b',3,'m','xxxx' union all
select 'b',4,'fm','xx' union all
select 'c',8,'m','xxx' union all
select 'c',9,'fm','xxxx'
)
select sno,MIN(snum) as snum,stuff((select ' '+sremark from test
where a.sno=sno for XML path('')),1,1,'') as sremark
from test as a group by a.sno
/*
sno snum sremark
---------------------
a 1 xx xxx xxxxx
b 2 x xxxx xx
c 8 xxx xxxx
----------------------
*/
------解决思路----------------------
中文也一样哦!