Here is a very simple, quick, but approximate solution. It is possible that CHECKSUM_AGG returns the same checksum for different sets of B.
DECLARE @T TABLE (A int, B int); INSERT INTO @T VALUES (1, 2),(1, 3),(2, 2),(2, 3),(2, 4),(3, 2),(3, 3),(4, 2),(4, 3),(4, 4); SELECT A ,CHECKSUM_AGG(B) AS CheckSumB ,ROW_NUMBER() OVER (PARTITION BY CHECKSUM_AGG(B) ORDER BY A) AS GroupNumber FROM @T GROUP BY A ORDER BY A, GroupNumber;
Result set
A CheckSumB GroupNumber ----------------------------- 1 1 1 2 5 1 3 1 2 4 5 2
For an exact solution group by A and combine all the values ββof B into a long (binary) string using either FOR XML, CLR, or the T-SQL function. You can then split ROW_NUMBER into this concatenated string to assign numbers to groups. As shown in other answers.
source share