您可以在子查询中尝试查询:
select referralName, count(id_referral) gCount From
(SELECT
CASE (id_referral )
WHEN 1 THEN 'Treatment'
WHEN 2 THEN 'Medication'
WHEN 3 THEN 'Medication'
WHEN 4 THEN 'Diagnosis / Tests'
WHEN 5 THEN 'Diagnosis / Tests'
ELSE 'Other'
END
referralName ,
id_referral
from referralDetails ) AS TABLE1 GROUP BY Test
或者您可以尝试使用额外的列返回列组计数
SELECT * FROM
(SELECT
CASE (id_referral )
WHEN 1 THEN 'Treatment'
WHEN 2 THEN 'Medication'
WHEN 3 THEN 'Medication'
WHEN 4 THEN 'Diagnosis / Tests'
WHEN 5 THEN 'Diagnosis / Tests'
ELSE 'Other'
END
referralName,
ROW_NUMBER() OVER (PARTITION BY (CASE (id_referral )
WHEN 1 THEN 'Treatment'
WHEN 2 THEN 'Medication'
WHEN 3 THEN 'Medication'
WHEN 4 THEN 'Diagnosis / Tests'
WHEN 5 THEN 'Diagnosis / Tests'
ELSE 'Other'
END ) ORDER BY id_referral ) AS NO,
COUNT(id_referral) OVER(PARTITION BY (CASE (id_referral )
WHEN 1 THEN 'Treatment'
WHEN 2 THEN 'Medication'
WHEN 3 THEN 'Medication'
WHEN 4 THEN 'Diagnosis / Tests'
WHEN 5 THEN 'Diagnosis / Tests'
ELSE 'Other'
END )) AS gCount,
* FROM referralDetails) AS TABLE1 WHERE no =1
或者
SELECT * FROM (SELECT ROW_NUMBER() OVER (PARTITION BY referralName ORDER BY id_referral) AS NO,
COUNT(id_referral) OVER(PARTITION BY referralName) AS gCount,
* FROM
(SELECT CASE (id_referral % 100 )
WHEN 1 THEN 'Treatment'
WHEN 2 THEN 'Medication'
WHEN 3 THEN 'Medication'
WHEN 4 THEN 'Diagnosis / Tests'
WHEN 5 THEN 'Diagnosis / Tests'
ELSE 'Other'
END AS referralName ,* FROM dbo.referralDetails) AS T1)AS T2 WHERE No = 1