Selecting data against numeric values saved as comma separated string - sql

I have two sql tables and looking for a sql query to select data against each numeric value in Table1.ValueID column from Table2.ValueDescription column and save result in Table3
Table1:
ID ValueID
1 1,12,14
2 3,5,15
3 2,6,13,16
Table2:
ValueID ValueDescription
1 Motor
2 Low
3 Failed
4 New Install
5 New Item
6 Max Value
7 AC Current
8 DC Current
9 Not Reached
10 NA
11 Cutoff
12 Manual
13 Automatic
14 Device Not Found
15 Halt
16 Renew
Expected Result:
Table3:
ID ValueID Result
1 1,12,14 Motor,Manual,Device Not Found
2 3,5,15 Failed,New Item,Halt
3 2,6,13,16 Low,Max Value,Automatic,Renew
Using SQL Server Management Studio
Here is the query I tried
SELECT Table1.ValueID,
Stuff((SELECT ',' + CAST(Table2.Description AS VARCHAR(100))
FROM Table2
WHERE Table1.ValueID LIKE Table2.ValueID
FOR Xml Path('')),1,1,'')
FROM Table1
what I am missing here?

If in fact you really using SQL Server 2017, you can use both the STRING_SPLIT and the STRING_AGG functions. They make for a very easy syntax.
IF OBJECT_ID('tempdb..#Table1', 'U') IS NOT NULL
DROP TABLE #Table1;
CREATE TABLE #Table1 (
ID INT NOT NULL PRIMARY KEY,
ValueID VARCHAR(50) NOT NULL
);
INSERT #Table1 (ID, ValueID) VALUES
(1, '1,12,14'),
(2, '3,5,15'),
(3, '2,6,13,16');
IF OBJECT_ID('tempdb..#Table2', 'U') IS NOT NULL
DROP TABLE #Table2;
CREATE TABLE #Table2 (
ValueID INT NOT NULL PRIMARY KEY,
ValueDescription VARCHAR(50) NOT NULL
);
INSERT #Table2(ValueID, ValueDescription) VALUES
(1, 'Motor'),
(2, 'Low'),
(3, 'Failed'),
(4, 'New Install'),
(5, 'New Item'),
(6, 'Max Value'),
(7, 'AC Current'),
(8, 'DC Current'),
(9, 'Not Reached'),
(10, 'NA'),
(11, 'Cutoff'),
(12, 'Manual'),
(13, 'Automatic'),
(14, 'Device Not Found'),
(15, 'Halt'),
(16, 'Renew');
--SELECT * FROM #Table1 t1;
--SELECT * FROM #Table2 t2;
--========================================================
SELECT
t1.ID,
t1.ValueID,
csv.Result
FROM
#Table1 t1
CROSS APPLY (
SELECT
Result = STRING_AGG(t2.ValueDescription, ',')
FROM
STRING_SPLIT(t1.ValueID, ',') ss
JOIN #Table2 t2
ON CONVERT(INT, ss.value) = t2.ValueID
) csv;
The results...
ID ValueID Result
----------- -------------- -----------------------------------
1 1,12,14 Motor,Manual,Device Not Found
2 3,5,15 Failed,New Item,Halt
3 2,6,13,16 Low,Max Value,Automatic,Renew
Edit:
-
-============================================================================
-- This is an idea that I've been kicking around for a little while now.
-- It's based on the SUSPICION that, when left to it's own devices. STRING_SPLIT
-- will always retun rows in the original order and attaching a row_number()
-- to the output, right out of the gate, will effectively serve as an "ItemNumber.
--============================================================================
SELECT
t1.ID,
t1.ValueID,
csv.Result
FROM
#Table1 t1
CROSS APPLY (
SELECT
Result = STRING_AGG(t2.ValueDescription, ',') WITHIN GROUP (ORDER BY rs.rn DESC) -- sort in the descending order for no real eason...
FROM (
SELECT
rn = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),
ValueID = CONVERT(INT, ss.value)
FROM
STRING_SPLIT(t1.ValueID, ',') ss
) rs
JOIN #Table2 t2
ON rs.ValueID = t2.ValueID
) csv;
ID ValueID Result
----------- ------------- --------------------------------
1 1,12,14 Device Not Found,Manual,Motor
2 3,5,15 Halt,New Item,Failed
3 2,6,13,16 Renew,Automatic,Max Value,Low

This will keep the proper sequence
Example
Select A.*
,B.*
From Table1 A
Cross Apply (
Select Result = Stuff((Select ',' +B2.ValueDescription
From (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace(A.ValueID,',','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) B1
Join Table2 B2 on B1.RetVal=B2.ValueID
Order by RetSeq
For XML Path ('')),1,1,'')
) B
Returns
ID ValueID Result
1 1,12,14 Motor,Manual,Device Not Found
2 3,5,15 Failed,New Item,Halt
3 2,6,13,16 Low,Max Value,Automatic,Renew
Oops -- Just saw you are 2017

It's not that much prettier but the new built-in functions in SQL Server 2017 do make this a little easier to follow, and can still be made to respect the order of the original list (well, I can't even tell if you intended to order by location in the list or by numerical order, since those are the same), then provided it is all integers and there are no duplicates:
;WITH explode(ID, ValueID, value, i) AS
(
SELECT t1.ID,
t1.ValueID,
TRY_CONVERT(int,f.value),
CHARINDEX(',' + f.value + ',', ',' + t1.ValueID + ',')
FROM dbo.Table1 t1
CROSS APPLY STRING_SPLIT(t1.ValueID, ',') AS f
)
SELECT x.ID, x.ValueID,
-- guarantee respect original order:
Result = STRING_AGG(t2.ValueDescription,',') WITHIN GROUP (ORDER BY x.i)
FROM explode AS x
INNER JOIN dbo.Table2 AS t2
ON x.value = t2.ValueID
GROUP BY x.ID, x.ValueID
ORDER BY x.ID;
If order doesn't matter, and you are sure there can be no duplicates or non-integers in the ValueID list in Table1, it is much simpler:
;WITH explode(ID, ValueID, value) AS
(
SELECT t1.ID, t1.ValueID, f.value
FROM dbo.Table1 t1
CROSS APPLY STRING_SPLIT(t1.ValueID, ',') AS f
)
SELECT x.ID, x.ValueID, STRING_AGG(t2.ValueDescription,',')
FROM explode AS x
INNER JOIN dbo.Table2 AS t2
ON x.value = t2.ValueID
GROUP BY x.ID, x.ValueID
ORDER BY x.ID;

You can do like
SELECT *,
STUFF(
(
SELECT ',' + ValueDescription
FROM T2
WHERE ',' + T1.ValueID + ',' LIKE '%,' + CAST(T2.ValueID AS VARCHAR) + ',%'
FOR XML PATH('')
),
1, 1, ''
) ValueDescription
FROM T1;
Returns:
+----+-----------+-------------------------------+
| ID | ValueID | ValueDescription |
+----+-----------+-------------------------------+
| 1 | 1,12,14 | Motor,Manual,Device Not Found |
| 2 | 3,5,15 | Failed,New Item,Halt |
| 3 | 2,6,13,16 | Low,Max Value,Automatic,Renew |
+----+-----------+-------------------------------+
Demo

Related

Need query to join table on column with comma separated

Table1
ID
Notes
ReasonID
1
Test1
[11,12]
2
Test2
[13,14]
Table 2
Reasonid
Name
11
Other1
12
Other2
13
Other3
14
Other4
Result should look like this, where Notes column from Table1 should concat with Name column from Table2.
ID
Final_Notes
1
Test1,Other1,Other2
2
Test2,Other3,Other4
If you use SQL Server 2017+, you may try to parse the ReasonID column as JSON, use an appropriate JOIN and then aggregate with STRING_AGG().
Sample data:
SELECT *
INTO Table1
FROM (VALUES
(1, 'Test1', '[11,12]'),
(2, 'Test2', '[13,14]')
) t (ID, Notes, ReasonID)
SELECT *
INTO Table2
FROM (VALUES
(11, 'Other1'),
(12, 'Other2'),
(13, 'Other3'),
(14, 'Other4')
) t (ReasonID, Name)
Statement:
SELECT
ID,
FinalNotes = CONCAT(
Notes,
',',
(
SELECT STRING_AGG(t2.Name, ',') WITHIN GROUP (ORDER BY CONVERT(int, j.[key]))
FROM OPENJSON(ReasonID) j
-- Important, JOIN with possible implicit conversion
JOIN Table2 t2 ON j.[value] = t2.ReasonID
)
)
FROM Table1
Result:
ID
FinalNotes
1
Test1,Other1,Other2
2
Test2,Other3,Other4
db<>fiddle
Please try the following solution.
It will work starting from SQL Server 2012 onwards.
It is using the following:
XML/XQuery to tokenize comma separated list of values.
FOR XML PATH to compose FinalNotes comma separated list.
SQL
-- DDL and sample data population, start
DECLARE #Table1 TABLE(ID INT, Notes VARCHAR(60), ReasonID VARCHAR(60));
INSERT INTO #Table1(ID, Notes, ReasonID) VALUES
(1, 'Test1', '[11,12]'),
(2, 'Test2', '[13,14]');
DECLARE #Table2 TABLE(Reasonid INT, Name VARCHAR(60));
INSERT INTO #Table2(Reasonid, Name) VALUES
(11, 'Other1'),
(12, 'Other2'),
(13, 'Other3'),
(14, 'Other4');
-- DDL and sample data population, end
DECLARE #separator CHAR(1) = ',';
;WITH rs AS
(
SELECT ID, Notes, Name
FROM #Table1 AS t
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
REPLACE(REPLACE(REPLACE(ReasonID,'[',''),']',''), #separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML)) AS t1(c)
CROSS APPLY c.nodes('/root/r/text()') AS t2(x)
INNER JOIN #Table2 AS t3 ON t3.Reasonid = x.value('.', 'INT')
)
SELECT ID, CONCAT(Notes
, (SELECT #separator + c.Name AS [text()]
FROM rs AS c
WHERE c.ID = p.ID
FOR XML PATH(''))) AS FinalNotes
FROM rs AS p
GROUP BY ID, Notes;
Output
+----+---------------------+
| ID | FinalNotes |
+----+---------------------+
| 1 | Test1,Other1,Other2 |
| 2 | Test2,Other3,Other4 |
+----+---------------------+
use SUBSTRING(string, 2, LEN(string)-2) for deleting [] and Parsename to split based on comma and join and concat as follows
Your data
DECLARE #Table1 TABLE(
ID INTEGER NOT NULL,
Notes VARCHAR(60) NOT NULL,
ReasonID VARCHAR(60) NOT NULL
);
INSERT INTO #Table1(ID, Notes, ReasonID)
VALUES
(1, 'Test1', '[11,12]'),
(2, 'Test2', '[13,14]');
DECLARE #Table2 TABLE(
Reasonid INTEGER NOT NULL,
Name VARCHAR(60) NOT NULL
);
INSERT INTO #Table2(Reasonid, Name)
VALUES
(11, 'Other1'),
(12, 'Other2'),
(13, 'Other3'),
(14, 'Other4');
your query
SELECT id,
Concat(notes, ',', T2.name, ',', T3.name) FinalNotes
FROM (SELECT id,
notes,
Parsename(Replace(SUBSTRING(ReasonID, 2, LEN(ReasonID)-2), ',', '.'), 2) R1,
Parsename(Replace(SUBSTRING(ReasonID, 2, LEN(ReasonID)-2), ',', '.'), 1) R2
FROM #table1) T1
join #table2 T2
ON T1.R1 = T2.reasonid
join #table2 T3
ON T1.R2 = T3.reasonid
by using XML
DROP TABLE IF EXISTS #t -- temporary table
select t1.ID,t1.Notes, Name into #t -- temporary table
from
(
SELECT A.ID,a.Notes,
Split.a.value('.', 'VARCHAR(100)') AS String
FROM (SELECT ID, Notes,
CAST ('<M>' + REPLACE(SUBSTRING(ReasonID, 2, LEN(ReasonID)-2) , ',', '</M><M>') + '</M>' AS XML) AS String
FROM #Table1) AS A CROSS APPLY String.nodes ('/M') AS Split(a)) t1
join #Table2 t2 on t1.String=t2.Reasonid
---XML Path
SELECT ID,concat(notes,',',
STUFF((SELECT ', ' + CAST(name AS VARCHAR(10)) [text()]
FROM #t t1
WHERE t1.ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ')) FinalNotes
FROM #t t
GROUP BY ID,notes

Row result manipulation

I have an existing query that retrieves this data:
Key Type TextF
--- ---- ------
1 R NULL
1 T TEST
1 T TEST2
2 R NULL
2 T FOO
3 R NULL
Scenario:
Row type R will always have a NULL on TextF. However if the Key has a type T data existing, I should place the TextF on R data, joining them with CRLF or char(13)
Expected output based on given data:
Key Type TextF
--- ---- ----------
1 R TEST TEST2
2 R FOO
3 R NULL
How can I achieve this through a query? I'm trying to make my existing query to be a subquery but I cant seem to make it work.
SELECT T0.*, *formatting here* FROM ( [myQuery] ) T0
I don't think it's the best solution but you could use the STUFF function to achieve your desired results:
SELECT t1.[Key],
'R' [Type],
STUFF((SELECT ' ' + t2.[TextF]
FROM yourTable t2
WHERE t2.[Key] = t1.[Key]
FOR XML PATH('')), 1, 1, '') [TextF]
FROM yourTable t1
GROUP BY t1.[Key]
You can use this.
DECLARE #MyTable TABLE ([Key] INT, Type VARCHAR(5), TextF VARCHAR(100))
INSERT INTO #MyTable VALUES
(1 ,'R', NULL),
(1 ,'T', 'TEST'),
(1 ,'T', 'TEST2'),
(2 ,'R', NULL),
(2 ,'T', 'FOO'),
(3 ,'R', NULL)
SELECT
T.[Key],
T.Type,
CASE WHEN Type = 'R' THEN REPLACE(STUFF(X.TextF,1,1,''),'|', CHAR(13)) ELSE T.TextF END TextF
FROM #MyTable T
OUTER APPLY( SELECT '|' + TextF FROM #MyTable T1
WHERE T.[Key] = T1.[Key]
AND T1.Type <> 'R'
AND T1.TextF IS NOT NULL FOR XML PATH('')) X(TextF)
WHERE T.Type = 'R'
Result:
Key Type TextF
----------- ----- -------------
1 R TEST
TEST2
2 R FOO
3 R NULL
In SQL Server 2017 you can use a new built-in function STRING_AGG
SELECT T0.[Key], T0.[Type],
(SELECT STRING_AGG (T1.TextF, CHAR(13)) AS TextF
FROM [myTable] T1
WHERE T1.[Type]='T' AND T1.[Key]=T0.[Key]
) TextF
FROM [myTable] T0
WHERE T0.[Type]='R'
Slightly different from other solutions--
DECLARE #MyTable TABLE ([Key] INT, Type VARCHAR(5), TextF VARCHAR(100))
INSERT INTO #MyTable VALUES
(1 ,'R', NULL),
(1 ,'T', 'TEST'),
(1 ,'T', 'TEST2'),
(2 ,'R', NULL),
(2 ,'T', 'FOO'),
(3 ,'R', NULL)
SELECT
T.[Key],
T.Type,
STUFF
((
SELECT ' ' + TextF
FROM #MyTable a
WHERE ( a.[Key] = T.[Key] )
FOR XML PATH('')
) ,1,2,'')
AS cusr
FROM #MyTable T
WHERE T.Type = 'R'
OUTPUT
Key Type cusr
----------- ----- --------------
1 R TEST TEST2
2 R FOO
3 R NULL
(3 rows affected)

SQL - string combine based on id

Need suggestion to split string in table 1, match its Ids with table 2 and concatenate the values.
Table - 1
Id Tbl1Col
1 2
2 2,4
3
4 6
5 3
Table - 2
Id Tbl2Col
1 E
2 F
3 M
4 U
5 P
6 C
7 N
8 G
Query -
SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = #Id
Now If #Id = 1, Output is F -- works fine
Now If #Id = 2, Output should be FU -- should not be F,U
Yuck! But you can use LIKE:
SELECT T2.Tbl2Col
FROM Table1 T1 LEFT JOIN
Table2 T2
WHERE ',' + T1.Tbl1Col + ',' LIKE '%,' + CAST(T2.Id as VARCHAR(255)) + ',%'
WHERE T1.Id = #Id;
You have a lousy data format, so this cannot make use of indexes. You should really have a separate table, with one row per Table1.id and Table2.id. Such a table is called a junction table or an association table.
create table dbo.Table01 (
Id int
, Col varchar(100)
);
create table dbo.Table02 (
Id int
, Col varchar(100)
);
insert into dbo.Table01 (Id, Col)
values (1, '2'), (2, '2, 4');
insert into dbo.Table02 (Id, Col)
values (1, 'E'), (2, 'F'), (4, 'U');
select
t.Id
, replace(STRING_AGG (t02.Col, ','), ',', '') as StringAgg
from dbo.Table01 t
cross apply string_split (t.Col, ',') as ss
inner join dbo.Table02 t02 on ss.value = t02.Id
group by t.id
Follow the next approach:-
1) Turning a Comma Separated string into individual rows via using CROSS APPLY with XML
2) Join the two tables with left join.
3) Concatenate many rows with same id via using STUFF & FOR XML
4) Use Replace function for removing comma.
Demo:-
declare #MyTable table (id int , Tbl1Col varchar(10))
insert into #MyTable values (1,'2'),(2,'2,4'),(3,''),(4,'6'),(5,'3')
declare #MyTable2 table (id int , Tbl2Col varchar(10))
insert into #MyTable2 values (1,'E'),(2,'F'),(3,'M'),(4,'U'),(5,'P'),(6,'C'),(7,'N'),(8,'G')
select a.id , Tbl2Col
into #TestTable
from
(
SELECT A.id,
Split.a.value('.', 'VARCHAR(100)') AS Tbl1Col
FROM
(
SELECT id,
CAST ('<M>' + REPLACE(Tbl1Col, ',', '</M><M>') + '</M>' AS XML) AS Data
FROM #MyTable
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) ) a
left join #MyTable2 b
on a.Tbl1Col = b.id
order by a.id
SELECT id, Tbl2Col =
Replace(STUFF((SELECT DISTINCT ', ' + Tbl2Col
FROM #TestTable b
WHERE b.id = a.id
FOR XML PATH('')), 1, 2, ''),',','')
FROM #TestTable a
GROUP BY id
Output:-
1 F
2 F U
3 NULL
4 C
5 M
References:-
Turning a Comma Separated string into individual rows
How to concatenate many rows with same id in sql?
Finally:-
Don't use this approach, and normalize your database instead , just use it as fun/training/trying .... etc code.

Comparings multiple parts of a string with separating characters `"` between two tables

I got two tables with strings. Now, those strings consists of different parts seperated by an ". For example:
table1:
---------------------
| 1 | hello"world |
---------------------
| 2 | hows"life"bro |
---------------------
table2:
-----------------------
| 1 | world"hello |
-----------------------
| 2 | hows"bro"life |
-----------------------
At the moment I got a query like this:
select * from table1 inner join table2
on table1.id = table2.id
where table1.colum2 = table2.colum2
The query I need should show both rows, because if you change the hello and the world from table1 you get world"hello which table2 does contain. How can I do this?
Thanks in advance
You need a split string function to do this
;WITH tab1
AS (SELECT *
FROM (VALUES ( 1,'hello"world' ),
(2,'hows"life"bro' )) t1 (id, NAME)
CROSS apply (SELECT *
FROM Delimitedsplit8k(t1.NAME, '"')) cs),
tab2
AS (SELECT *
FROM (VALUES ( 1,'world"hello' ),
(2,'hows"bro"life' )) t2 (id, NAME)
CROSS apply (SELECT *
FROM Delimitedsplit8k(t2.NAME, '"')) cs)
SELECT DISTINCT t1.id,
t1.NAME,
t2.id,
t2.NAME
FROM tab1 t1
JOIN tab2 t2
ON t1.Item = t2.Item
Create the split string from here
Tally OH! An Improved SQL 8K “CSV Splitter” Function
You can convert column2 to xml and use xquery to sort the values and compare.
declare #T1 table (id int, col varchar(max))
insert into #T1 (id, col) values (1, 'hellow"world'), (2, 'a"b"c')
declare #T2 table (id int, col varchar(max))
insert into #T2 (id, col) values (1, 'world"hellow'), (2, 'b"c"a')
select *
from #T1 as t1
inner join #T2 as t2 on t1.id = t2.id
where
cast('<a>' + replace(t1.col, '"', '</a><a>') + '</a>' as xml).query('for $x in /a order by $x return string($x)').value('/', 'varchar(max)') =
cast('<a>' + replace(t2.col, '"', '</a><a>') + '</a>' as xml).query('for $x in /a order by $x return string($x)').value('/', 'varchar(max)')

How to concatenate all strings from a certain column for each group

Suppose I have this table [Table1]
Name Mark
------- ------
ABC 10
DEF 10
GHI 10
JKL 20
MNO 20
PQR 30
What should be my SQL statement to retrieve a record that looks like this:
(group by [mark]).
I have done the 1 and 2 columns but don't know how to accomplish the third column (concat the [name] with the same [mark])
mark count names
---- ----- -----------
10 3 ABC,DEF,GHI
20 2 JKL,MNO
30 1 PQR
I'm using Microsoft SQL.
Please help. Thanks
If MS SQL 2005 or higher.
declare #t table([name] varchar(max), mark int)
insert #t values ('ABC', 10), ('DEF', 10), ('GHI', 10),
('JKL', 20), ('MNO', 20), ('PQR', 30)
select t.mark, COUNT(*) [count]
,STUFF((
select ',' + [name]
from #t t1
where t1.mark = t.mark
for xml path(''), type
).value('.', 'varchar(max)'), 1, 1, '') [values]
from #t t
group by t.mark
Output:
mark count values
----------- ----------- --------------
10 3 ABC,DEF,GHI
20 2 JKL,MNO
30 1 PQR
Here's a performance-related answer!
http://jerrytech.blogspot.com/2010/04/tsql-concatenate-strings-1-2-3-and.html
Using XML functions in a large query is a performance killer.
Using a CTE is a performance superstar.
Check out the link, it will explain how.
I admit the work to accomplish it is more.
But the result is milliseconds over millions of rows.
polishchuks solution is more elegant, but this is basically the same thing, we just deal with the trailing comma differently.
CREATE TABLE #Marks(Name nchar(3), Mark int)
INSERT INTO #Marks
SELECT 'ABC', 10 UNION ALL
SELECT 'DEF', 10 UNION ALL
SELECT 'GHI', 10 UNION ALL
SELECT 'JKL', 20 UNION ALL
SELECT 'MNO', 20 UNION ALL
SELECT 'PQR', 30
SELECT
mark,
[count],
CASE WHEN Len(Names) > 0 THEN LEFT(Names, LEN(Names) -1) ELSE '' END names
FROM
(
SELECT
Mark,
COUNT(Mark) AS [count],
(
SELECT DISTINCT
Name + ', '
FROM
#Marks M1
WHERE M1.Mark = M2.Mark
FOR XML PATH('')
) Names
FROM #Marks M2
GROUP BY Mark
) M
Loosely based on Itzik Ben-Gan, Inside Microsoft SQL Server 2005: T-SQL Programming, p. 215:
IF OBJECT_ID('dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1 ;
GO
CREATE TABLE dbo.Table1 ( Name VARCHAR(10), Mark INT ) ;
INSERT INTO dbo.Table1 ( Name, Mark ) VALUES ( 'ABC', 10 ) ;
INSERT INTO dbo.Table1 ( Name, Mark ) VALUES ( 'DEF', 10 ) ;
INSERT INTO dbo.Table1 ( Name, Mark ) VALUES ( 'GHI', 10 ) ;
INSERT INTO dbo.Table1 ( Name, Mark ) VALUES ( 'JKL', 20 ) ;
INSERT INTO dbo.Table1 ( Name, Mark ) VALUES ( 'MNO', 20 ) ;
INSERT INTO dbo.Table1 ( Name, Mark ) VALUES ( 'PQR', 30 ) ;
WITH DelimitedNames AS
(
SELECT Mark, T2.Count,
( SELECT Name + ',' AS [text()]
FROM dbo.Table1 AS T1
WHERE T1.Mark = T2.Mark
ORDER BY T1.Mark
FOR XML PATH('')) AS Names
FROM ( SELECT Mark, COUNT(*) AS Count FROM dbo.Table1 GROUP BY Mark ) AS T2
)
SELECT Mark, Count, LEFT(Names, LEN(NAMES) - 1) AS Names
FROM DelimitedNames ;