Alright so I have two tables. Table1 has an reference number column (A), and a second column that has a string of randomness (B). Table2 has only one column with a list of value
Split Function
CREATE FUNCTION [dbo].[udf_Split]
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
Your Data
DECLARE @Table_1 TABLE ([A] INT,[B] VARCHAR(1000))
INSERT INTO @Table_1 VALUES
(24,'BLUE; KITTEN; WHITE; PINK; SLOPE; GREEN'),
(51,'GREEN; CLOUDY; WHITE; CHIPS'),
(78,'PATRIOTS; PINK; PINK; WHITE'),
(22,'WHITE; RED; TREES; AMY; GREEN')
DECLARE @Table_2 TABLE (ColumnName VARCHAR(100))
INSERT INTO @Table_2 VALUES
('BLUE'),('WHITE'),('PINK'),('BROWN')
Query
SELECT T2.ColumnName, TotalNums
FROM
(SELECT Data, COUNT(DATA) TotalNums
FROM @Table_1 t CROSS APPLY (SELECT * FROM [dbo].[udf_Split](t.B, ';'))C
GROUP BY Data) T1
RIGHT JOIN @Table_2 T2
ON T1.Data = T2.ColumnName
Result Set
╔════════════╦═══════════╗
║ ColumnName ║ TotalNums ║
╠════════════╬═══════════╣
║ BLUE ║ 1 ║
║ WHITE ║ 4 ║
║ PINK ║ 3 ║
║ BROWN ║ NULL ║
╚════════════╩═══════════╝