一条常见的行合并问题(SQL)
这样的问题一般写个自定义函数,由orig_word 统计similar_word,就可以实现。
来自一朋友叫hxd001_810,使用自定义函数的方法:
用函数解决之。代码如下:
--创建一个合并的函数
create function f_hb(@original_id varchar(10))
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' +b.word
from similarword a inner join dbo.originalword b on a.similar_id=b.ID
where original_id = @original_id
set @str = right(@str , len(@str) - 1)
return(@str)
End
go
--调用自定义函数得到结果:
select distinct a.original_id [originalword.ID],b.word [orig_word],dbo.f_hb(a.original_id) as similar_id
from similarword a inner join dbo.originalword b on a.original_id=b.ID
go
返回:
originalword.ID orig_word similar_id
--------------- ------------- -----------
101 about abound
102 abound about
103 beard beast
104 boast beast
105 beast beard,boast
(所影响的行数为 5 行)
从性能分析,个人认为使用自定义函数性能比使用循环语句效率低一点,特别是在处理大量数据时候。
以下是自己写的一个使用循环的方法:
SET NOCOUNT ON
CREATE TABLE originalword(id int ,word nvarchar(30))
CREATE TABLE similarword (ID int ,original_id int,similar_id int)
GO
INSERT INTO originalword
SELECT 101, 'about' UNION ALL
SELECT 102, 'abound' UNION ALL
SELECT 103, 'beard' UNION ALL
SELECT 104, 'boast' UNION ALL
SELECT 105, 'beast'
INSERT INTO similarword
SELECT 1, 101, 102 UNION ALL
SELECT 2, 102, 101 UNION ALL
SELECT 3, 103, 105 UNION ALL
SELECT 4, 105, 103 UNION ALL
SELECT 5, 104, 105 UNION ALL
SELECT 6, 105, 104
GO
DECLARE @Result TABLE(id int IDENTITY(1,1),[originalword.ID] int,orig_word nvarchar(30),similar_word nvarchar(30))
INSERT INTO @Result ([originalword.ID],orig_word) SELECT * FROM originalword
DECLARE @i int
,@j int
,@similar_word nvarchar(200)
SELECT @i=1,@j=ISNULL(COUNT(1),0) FROM @Result
WHILE @i<=@j
BEGIN
SET @similar_word=''
SELECT @similar_word=@similar_word+word+',' FROM
(SELECT B.word FROM similarword A INNER JOIN originalword B ON A.original_id=B.ID
AND EXISTS(SELECT 1 FROM @Result C WHERE C.[originalword.ID]=A.original_id AND C.ID=@i)) Tmp
IF(ISNULL(@similar_word,'')<>'')
UPDATE @Result SET similar_word=SUBSTRING(@similar_word,1,LEN(@similar_word)-1) WHERE ID=@i
SET @i=@i+1
END
SELECT [originalword.ID],orig_word,similar_word FROM @Result
GO
DROP TABLE originalword,similarword
GO
原帖子:http://www.itpub.net/thread-903644-1-2.html
完。