求一SQL
Table
id name title
1 AA 1.AA
2 BB 2.BB
3 CC 3.CC
1 AA 1.BB
我要把相同ID,NAME的title 合併成一行
顯示結果為
id name title
1 AA 1.AA,1.BB
2 BB 2.BB
3 CC 3.CC
------解决方案----------------------需要寫一個合併函數
--建立測試環境
Create Table TEST
(id Int,
name Varchar(10),
title Varchar(10))
Insert TEST Select 1, 'AA ', '1.AA '
Union All Select 2, 'BB ', '2.BB '
Union All Select 3, 'CC ', '3.CC '
Union All Select 1, 'AA ', '1.BB '
GO
--建立合併函數
Create Function Gettitle(@id Int, @name Varchar(10))
Returns Varchar(8000)
As
Begin
Declare @S Varchar(8000)
Select @S = ' '
Select @S = @S + ', ' + Rtrim(title) From TEST Where id =@id And name = @name
Select @S = Stuff(@S , 1, 1 , ' ')
Return @S
End
GO
--測試
Select
id,
name,
dbo.Gettitle(id, name) As title
From
TEST
Group By
id,
name
GO
--刪除測試環境
Drop Table TEST
Drop Function Gettitle
--結果
/*
id name title
1 AA 1.AA,1.BB
2 BB 2.BB
3 CC 3.CC
*/
------解决方案--------------------使用函数
---建立函数
create function GetTitle
(@id int,@name varchar(30))
returns varchar(1000)
as
begin
declare @title varchar(1000)
set @title= ' '
select @title=@title + ', ' + title from t1 where id=@id and name=@name
set @title=stuff(@title,1,1, ' ')
return @title
end
---获取数据
select id,name,dbo.getTitle(id,name) from t1
group by id,name
------解决方案--------------------paoluo(一天到晚游泳的鱼)
正解
------解决方案--------------------Declare @S Varchar(8000)
Select @S = ' '
Select @S = @S + ', ' + Rtrim(title) From TEST Where id =@id And name = @name
Select @S = Stuff(@S , 1, 1 , ' ')
Return @S
------解决方案--------------------行列转换--合并
有表A,
id pid
1 1
1 2
1 3
2 1
2 2
3 1
如何化成表B:
id pid
1 1,2,3
2 1,2
3 1
创建一个合并的函数
create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str= '
select @str=@str+ ', '+cast(pid as varchar) from 表A where id=@id
set @str=right(@str,len(@str)-1)
return(@str)
End
go