日期:2014-05-19  浏览次数:20550 次

一个简单的问题,在线等待----

create   table   #t   (a   int   ,b   varchar(1000))
insert   into   #t
select   1, '1 '
union
select   1, '2 '
union
select   1, '3 '
union
select   1, '4 '
union
select   1, '5 '
union
select   2, '6 '
union
select   2, '7 '
union
select   3, '8 '

select   *   from   #t
如果a   相同,满足4个为一组
结果如下
a       b
1       1;2;3;4
1       5
2       6;7
3       8


------解决方案--------------------
--我保证现在好了(可恶的临界问题)
create table #t (a int ,b varchar(1000),ii int,i int)
insert into #t(a,b)
select 1, '1 '
union
select 1, '2 '
union
select 1, '3 '
union
select 1, '4 '
union
select 1, '5 '
union
select 2, '6 '
union
select 2, '7 '
union
select 3, '8 '

declare @a int,@b varchar(8000),@bb varchar(8000),@i int,@ii int
select @i = 0,@ii = 0
update #t
set @bb = case when a = @a and @i < 2 then @bb + '; ' + b else b end
,@ii = case when a = @a and @i < 2 then @ii else @ii+1 end
,@i = case when a = @a and @i < 2 then @i + 1 else 1 end
,@a = a,@b = b,b = @bb ,ii = @ii,i = @i

select a,max(b)
from #t
group by a,ii
order by a,ii

drop table #t
a
----------- --------
1 1;2
1 3;4
1 5
2 6;7
3 8