This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output to generate the group of sequences.
Input Data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Name SeqNo ---- ----------- A 1 A 2 A 3 B 1 B 2 C 1 C 2 C 3 D 1 D 2 D 3 D 4 D 5 |
Expected Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Name SequenceNo_Groups ---- -------------------- A 11,12,13 A 11,12,13 A 11,12,13 B 21,22 B 21,22 C 31,32,33 C 31,32,33 C 31,32,33 D 41,42,43,44,45 D 41,42,43,44,45 D 41,42,43,44,45 D 41,42,43,44,45 D 41,42,43,44,45 |
Create a table with sample data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
CREATE TABLE TestSequences ( Name VARCHAR(3) ,SeqNo INT ) GO INSERT INTO TestSequences VALUES ('A' ,1) ,('A' ,2) ,('A' ,3) ,('B' ,1) ,('B' ,2) ,('C' ,1) ,('C' ,2) ,('C' ,3) ,('D' ,1) ,('D' ,2) ,('D' ,3) ,('D' ,4) ,('D' ,5) GO |
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
;WITH CTE AS ( SELECT b.Name , CAST(rnk * 10 + SeqNo AS VARCHAR(3)) rnk FROM ( SELECT * , ROW_NUMBER() OVER ( ORDER BY (SELECT NULL) ) rnk FROM ( SELECT DISTINCT Name FROM TestSequences ) a ) b INNER JOIN TestSequences a on b.Name = a.Name ) SELECT Name, STUFF ((SELECT ',' + rnk FROM CTE w WHERE w.Name = t.Name FOR XML PATH('')) , 1,1,'') SequenceNo_Groups FROM CTE t |
Please try the different solution for this puzzle and share it via comment...