I use a UDF for things like this. If that could work for you:
CREATE FUNCTION [dbo].[UDF_StringDelimiter]
/*********************************************************
** Takes Parameter "LIST" and transforms it for use **
** to select individual values or ranges of values. **
** **
** EX: 'This,is,a,test' = 'This' 'Is' 'A' 'Test' **
*********************************************************/
(
@LIST VARCHAR(8000)
,@DELIMITER VARCHAR(255)
)
RETURNS @TABLE TABLE
(
[RowID] INT IDENTITY
,[Value] VARCHAR(255)
)
WITH SCHEMABINDING
AS
BEGIN
DECLARE
@LISTLENGTH AS SMALLINT
,@LISTCURSOR AS SMALLINT
,@VALUE AS VARCHAR(255)
;
SELECT
@LISTLENGTH = LEN(@LIST) - LEN(REPLACE(@LIST,@DELIMITER,'')) + 1
,@LISTCURSOR = 1
,@VALUE = ''
;
WHILE @LISTCURSOR <= @LISTLENGTH
BEGIN
INSERT INTO @TABLE (Value)
SELECT
CASE
WHEN @LISTCURSOR < @LISTLENGTH
THEN SUBSTRING(@LIST,1,PATINDEX('%' + @DELIMITER + '%',@LIST) - 1)
ELSE SUBSTRING(@LIST,1,LEN(@LIST))
END
;
SET @LIST = STUFF(@LIST,1,PATINDEX('%' + @DELIMITER + '%',@LIST),'')
;
SET @LISTCURSOR = @LISTCURSOR + 1
;
END
;
RETURN
;
END
;
The UDF takes two parameters: A string to be split, and the delimiter to split by. I've been using it for all sorts of different things over the years, because sometimes you need to split by a comma, sometimes by a space, sometimes by a whole string.
Once you have that UDF, you can just do this:
DECLARE @TABLE TABLE
(
Attribute_ID INT
,Value VARCHAR(55)
,Entity_ID INT
);
INSERT INTO @TABLE VALUES (188, '48,51,94', 1);
INSERT INTO @TABLE VALUES (188, '43,22', 2);
INSERT INTO @TABLE VALUES (188, '43,22', 3);
INSERT INTO @TABLE VALUES (188, '43,22', 6);
INSERT INTO @TABLE VALUES (190, '33,11', 10);
INSERT INTO @TABLE VALUES (190, '90,61', 12);
INSERT INTO @TABLE VALUES (190, '90,61', 15);
SELECT
T1.Attribute_ID
,T2.Value
,COUNT(T2.Value) AS Counter
FROM @TABLE T1
CROSS APPLY dbo.UDF_StringDelimiter(T1.Value,',') T2
GROUP BY T1.Attribute_ID,T2.Value
ORDER BY T1.Attribute_ID ASC, Counter DESC
;
I did an ORDER BY
Attribute_ID ascending and then the Counter descending so that you get each Attribute_ID with the most common repeating values first. You could change that, of course.
Returns this:
Attribute_ID Value Counter
-----------------------------------
188 43 3
188 22 3
188 94 1
188 48 1
188 51 1
190 61 2
190 90 2
190 11 1
190 33 1