Neither in sql 2000 nor in sql 2005, there is no aggregation function for strings,
so when we deal with the following requirements, it will be more troublesome:
there is a table tb, as follows:
id value
1 aa
1 bb
2 aaa
2 bbb
2 ccc
need to get the result:
id values
1 aa,bb
2 aaa,bbb,ccc
ie group by id, find the sum of value (addition of strings)
- Old solution
– 1. Create a processing function
CREATE FUNCTION dbo.f_str(@id int)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @r varchar(8000)
SET @r =''
SELECT @r = @r +',' + value
FROM tb
WHERE id=@id
RETURN STUFF(@r, 1, 1,'')
END
GO
-call function
SELECt id, values=dbo.f_str(id)
FROM tb
GROUP BY id
– 2. New solution
– sample data
DECLARE @t TABLE(id int, value varchar(10))
INSERT @t SELECT 1,'aa'
UNION ALL SELECT 1,'bb'
UNION ALL SELECT 2,'aaa'
UNION ALL