Multiple rows of SQL query merged into one line

Source: Internet
Author: User

Problem Description:
Neither in SQL 2000, nor in SQL 2005, does the aggregate function of the string be provided,
Therefore, when we are dealing with the following requirements, it will be more troublesome:
There are table TB, as follows:
ID value
----- ------
1 AA
1 BB
2 AAA
2 BBB
2 CCC
Need to get results:
ID values
------ -----------
1 AA,BB
2 AAA,BBB,CCC
That is, the group by ID, the sum of the value (string addition)

1. The old solution

--1. Creating a handler 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 [email protected]
RETURN STUFF (@r, 1, 1, ")
END
GO
--Call function

SELECt ID, values=dbo.f_str (ID)
From TB
GROUP by ID

--2. A 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 SELECT 2, ' BBB '
UNION all SELECT 2, ' CCC '

--Query processing
SELECT *
From (
SELECT DISTINCT
Id
From @t
) A
OUTER APPLY (
SELECT
[Values]= STUFF (replace (replace (
(
SELECT value from @t N
WHERE id = a.id
For XML AUTO
), ' <n value= ' ', ', '), '/> ', ', 1, 1, ')
) N

/*--Results
ID values
----------- ----------------
1 AA,BB
2 AAA,BBB,CCC
(2 rows affected)
--*/

Multiple rows of SQL query merged into one line

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.