高手请帮我写下这条高难度SQL语句???
有一张表table,如下
col1 col2
101 aaa
101 bbb
101 ccc
102 ddd
102 eee
我想用一条SQL语句得到如下的结果(不要用函数和存储过程,因为表太大,用以后太慢),
101 aaabbbccc
102 dddeee
请问用一条SQL语句如何实现???
------解决方案--------------------不用函数估计挺困难,期待高人
------解决方案--------------------declare @a table (col1 int,col2 varchar(30))
insert @a
select '101 ', 'aaa '
union all
select '101 ', 'bbb '
union all
select '101 ', 'ccc '
union all
select '102 ', 'ddd '
union all
select '102 ', 'eee '
select * from (select distinct col1 from @a) A
outer apply( select col2=stuff(replace(replace(
(select col2 from @a X where col1=A.col1 for XML AUTO), ' <X col2= " ', ' '), ' "/> ', ' ')
,1,1, ' '))X
(5 行受影响)
col1 col2
----------- ----------------------------------------------------------------------------------------------------------------
101 aabbbccc
102 ddeee
(2 行受影响)
------解决方案--------------------,1,1, ' '))X 改为,1,0, ' '))X
------解决方案--------------------(5 行受影响)
col1 col2
----------- -----------
101 aaabbbccc
102 dddeee
(2 行受影响)
------解决方案--------------------楼上的是SQL2005吧?
------解决方案--------------------嗯
------解决方案----------------------临时表法
create table T(col1 int, col2 varchar(10))
insert T select 101, 'aaa '
union all select 101, 'bbb '
union all select 101, 'ccc '
union all select 102, 'ddd '
union all select 102, 'eee '
select col1, col2=cast(col2 as varchar(1000))
into #T
from T
order by col1
declare @col1 int, @col2 varchar(1000)
update #T set
@col2=case when col1=@col1 then @col2+col2 else col2 end,
@col1=col1,
col2=@col2
select col1, col2=max(col2) from #T
group by col1
--result
col1 col2
----------- ---------
101 aaabbbccc
102 dddeee
(2 row(s) affected)
------解决方案--------------------create table T(col1 int, col2 varchar(10))
insert T select 101, 'aaa '
union all select 101, 'bbb '
union all select 101, 'ccc '
union all select 102, 'ddd '
union all select 102, 'eee '
--创建一个合并的函数
create function f_hb(@a int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ' '