I am facing a problem with a SQL
query. This is my table structure:
DECLARE @tab TABLE
(
Id INT IDENTITY,
Rid INT,
Address1 VARCHAR(50),
City VARCHAR(20)
)
INSERT INTO @tab VALUES (56, 'Test1', 'New York')
INSERT INTO @tab VALUES (1253, 'Test1', 'Delhi')
INSERT INTO @tab VALUES (56, 'Address5', 'Cali')
INSERT INTO @tab VALUES (1253, 'Address5', 'Delhi')
SELECT * FROM @tab
My query:
SELECT
Address1, STUFF((SELECT ',' + CONVERT(Varchar, Id)
FROM @tab TR
WHERE TR.Rid IN (56, 1253)
GROUP BY Id, Rid, Address1
FOR XML PATH('')), 1, 1, '') AS addid
FROM
@tab T
WHERE
T.Rid IN (56,1253)
GROUP BY
T.Address1
It is showing me all the Ids in comma wise, while I want to show the Ids Address
wise like 1,2
in the first column and 3,4
in the second column, ie Ids should be group by Address1.
Thanks
You need to filter TR.Address1
= T.Address1
instead of TR.Rid IN (56, 1253)
SELECT
Address1, STUFF((SELECT ',' + CONVERT(Varchar, Id)
FROM @tab TR
WHERE TR.Address1 = T.Address1 // Adjust the condition here
GROUP BY Id, Rid, Address1
FOR XML PATH('')), 1, 1, '') AS addid
FROM
@tab T
WHERE
T.Rid IN (56,1253)
GROUP BY
T.Address1
You need a correlated subquery. I would suggest writing the query as:
SELECT Address1,
STUFF((SELECT ',' + CONVERT(Varchar(MAX), Id)
FROM tab TR
WHERE TR.Address1 = T.Address1
FOR XML PATH('')
), 1, 1, '') AS addid
FROM tab T
WHERE T.Rid IN (56, 1253)
GROUP BY Address1
Notes:
varchar
without a length in SQL Server. The length varies by context and it introduces hard-to-debug errors.T.Rid
in the subquery. For your sample data, it is not necessary.Here is a db<>fiddle.
In more recent versions of SQL Server, you would simply use string_agg()
-- so you will be able to forget this XML hack.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.