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

group by 问题,能否通过一句SQL实现?
A           55
A           44
A           33
A           22

能否显示为:
A           55   44   33   22

------解决方案--------------------
--創建函數
Create Function F_TEST(@Col1 Varchar(10))
Returns Varchar(1000)
As
Begin
Declare @S Varchar(1000)
Select @S = ' '
Select @S = @S + ' ' + Cast(Col2 As Varchar) From 表 Where Col1 = @Col1
Return @S
End
GO
--測試
Select
Col1,
dbo. F_TEST(Col1) As Col2
From

Group By
Col1
GO
------解决方案--------------------
--测试环境
declare @tb table(col1 varchar(10),col2 varchar(10))

insert @tb select 'A ', '55 '
union all select 'A ', '44 '
union all select 'A ', '33 '
union all select 'A ', '22 '
union all select 'B ', '11 '


declare @col2_all varchar(100)
set @col2_all = ' '
select @col2_all = @col2_all + col2 + ' '
from @tb
where col1 = 'A '

select 'A ',@col2_all

--结果
A 55 44 33 22