SQL Server:计算文本出现的次数

时间:2014-03-25 14:46:18

标签: sql sql-server

我试图简单地计算次数"增长","风险"和"效率"发生在oppcat列中。这是当前的输出似乎并没有像我想的那样添加它们:http://i.imgur.com/zv6HdI9.jpg

 declare @MainHospital varchar(50)='hospital 1';
SELECT mainhospital,
       SUM(CASE WHEN [oppcat] = 'Growth' THEN 1 ELSE 0 END) as "Growth",
       SUM(CASE WHEN [oppcat] = 'Risk' THEN 1 ELSE 0 END) as "Risk",
       SUM(CASE WHEN [oppcat] = 'Efficiency' THEN 1 ELSE 0 END) as "Efficiency"
FROM Survey
WHERE MainHospital = @MainHospital
GROUP BY MainHospital;

奇怪的是,此查询返回3表示风险,因此不确定上述原因是什么

SELECT COUNT(*)
FROM Survey 
WHERE oppcat = 'Risk';

4 个答案:

答案 0 :(得分:0)

这是另一种方法:

DECLARE @MainHospital varchar(50)='hospital 1';
SELECT mainhospital, oppcat, COUNT(oppcat)
FROM Survey
WHERE MainHospital = @MainHospital
AND oppcat IN ('Growth','Risk','Efficiency')
GROUP BY MainHospital, oppcat;

答案 1 :(得分:0)

这不会起作用的一个原因是,如果您在操作中使用区分大小写的排序规则。看看是否有效:

SELECT mainhospital,
       SUM(CASE WHEN lower(oppcat) = 'growth' THEN 1 ELSE 0 END) as "Growth",
       SUM(CASE WHEN lower(oppcat) = 'risk' THEN 1 ELSE 0 END) as "Risk",
       SUM(CASE WHEN lower(oppcat) = 'efficiency' THEN 1 ELSE 0 END) as "Efficiency"
FROM Survey
WHERE MainHospital = @MainHospital
GROUP BY MainHospital;

答案 2 :(得分:0)

此查询:

SELECT COUNT(*) FROM Survey WHERE oppcat = 'Risk';

返回3,因为您没有按主题医院过滤和分组。

请尝试一下,看看会有什么回报:

SELECT
SUM(CASE WHEN [oppcat] = 'Growth' THEN 1 ELSE 0 END) as "Growth",
SUM(CASE WHEN [oppcat] = 'Risk' THEN 1 ELSE 0 END) as "Risk",
SUM(CASE WHEN [oppcat] = 'Efficiency' THEN 1 ELSE 0 END) as "Efficiency"
FROM Survey

答案 3 :(得分:-3)

我认为不是SUM您必须使用COUNT

declare @MainHospital varchar(50)='hospital 1';
SELECT mainhospital,
       COUNT(CASE WHEN [oppcat] = 'Growth' THEN 1 ELSE 0 END) as "Growth",
       COUNT(CASE WHEN [oppcat] = 'Risk' THEN 1 ELSE 0 END) as "Risk",
       COUNT(CASE WHEN [oppcat] = 'Efficiency' THEN 1 ELSE 0 END) as "Efficiency"
FROM Survey
WHERE MainHospital = @MainHospital
GROUP BY MainHospital;