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 as referralName ,
count(id_referral) gCount
from referralDetails
group by referralName
我收到错误
无效的列名称'referralName'
答案 0 :(得分:1)
您无法在GROUP BY
中引用列别名,因此您有两种选择。
您可以重复使用CASE
中的GROUP BY
:
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 as referralName ,
count(id_referral) gCount
from referralDetails
group 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
或者您可以将查询包装在子查询中:
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 as referralName ,
id_referral
from referralDetails
) d
group by referralName
答案 1 :(得分:1)
您可以在子查询中尝试查询:
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
答案 2 :(得分:1)
请尝试使用以下查询
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 as referralName ,
id_referral
from referralDetails) tbl
group by referralName