Пример данных
DECLARE @Policy AS TABLE (PolicyNo VARCHAR(100) , PolType VARCHAR(100) ,MyRejectionCode VARCHAR(100))
INSERT INTO @Policy
SELECT 'Pol1','S','M101' UNION ALL
SELECT 'Pol2','S','M101,M102' UNION ALL
SELECT 'Pol3','S','M104' UNION ALL
SELECT 'Pol4','F','M105,M107,M108' UNION ALL
SELECT 'Pol5','F','M106' UNION ALL
SELECT 'Pol6','F','M107'
DECLARE @RejectionMapping AS Table ( MyRejCode VARCHAR(100), StandardRejCode VARCHAR(100))
INSERT INTO @RejectionMapping
SELECT 'M101','S101' UNION ALL
SELECT 'M102','S102' UNION ALL
SELECT 'M103','S103' UNION ALL
SELECT 'M104','S104' UNION ALL
SELECT 'M105','S101' UNION ALL
SELECT 'M106','S102' UNION ALL
SELECT 'M107','S103' UNION ALL
SELECT 'M108','S104'
Теперь нам нужно разделить запятые данными в одну строку в формате xml.Затем необходимо объединить обе таблицы, используя внутреннее соединение, и, наконец, найти количество вхождений "PolType"
;WITH Cte
AS
(
SELECT PolicyNo,PolType,Split.a.value ('.','nvarchar(max)') AS MyRejectionCode
FROM
(
SELECT PolicyNo, PolType,
CAST('<S>'+REPLACE(MyRejectionCode,',','</S><S>')+'</S>' AS XML) AS MyRejectionCode
FROM @Policy
)AS A
CROSS APPLY MyRejectionCode.nodes('S') AS Split(a)
)
SELECT R.StandardRejCode,
ISNULL(SUM(CASE WHEN PolType = 'S' THEN 1 ELSE 0 END),0) AS S_Pol_Type_Count,
ISNULL(SUM(CASE WHEN PolType = 'F' THEN 1 ELSE 0 END),0) AS F_Pol_Type_Count
FROM Cte c
INNER JOIN @RejectionMapping R
ON R.MyRejCode = c.MyRejectionCode
GROUP BY R.StandardRejCode
Результат
StandardRejCode S_Pol_Type_Count F_Pol_Type_Count
------------------------------------------------------
S101 2 1
S102 1 1
S103 0 2
S104 1 1