Вы можете попробовать с этим ниже код CTE -
WITH CTE AS
(
SELECT Prov,Patient, 3 CNT
FROM your_table
WHERE YEAR(ServiceDate) = 2019
AND MONTH(ServiceDate) = 1
AND (
LEFT(Code,1) = 'F' OR RIGHT(Code,1) = 'G'
)
GROUP BY Prov,Patient
HAVING COUNT(Code) IN (4,5)
UNION ALL
SELECT Prov,Patient, COUNT(Code)
FROM your_table
WHERE YEAR(ServiceDate) = 2019
AND MONTH(ServiceDate) = 1
AND (
LEFT(Code,1) = 'F' OR RIGHT(Code,1) = 'G'
)
GROUP BY Prov,Patient
HAVING COUNT(Code) NOT IN (4,5)
UNION ALL
SELECT Prov,Patient, COUNT(Code)
FROM your_table
WHERE YEAR(ServiceDate) = 2019
AND MONTH(ServiceDate) = 1
AND LEFT(Code,1) <> 'F'
AND RIGHT(Code,1) <> 'G'
GROUP BY Prov,Patient
)
SELECT Prov, SUM(CNT) ChargeCount
FROM CTE
GROUP BY Prov
Выход -
Prov ChargeCount
Pv1 3
PV2 4