SQL Server:简单的COUNT查询

时间:2014-03-20 17:00:42

标签: sql sql-server

我试图计算次数" on"发生在多个列中。第一个查询返回我想要的内容,但是当我尝试第二个查询时,它只返回没有结果的列标题。如果有人能告诉我错误的原因,我只是回到sql。

此查询返回所需的结果:

DECLARE @MainHospital varchar(50)='HOSPITAL 1';

SELECT 
    mainhospital, COUNT([chkInpatient]) as 'Inpatient Count'
FROM 
    SurveyPicList
WHERE 
    MainHospital = @MainHospital 
    AND chkInpatient = 'on'
GROUP BY 
    MainHospital

这只返回5个列标题,但没有结果:

DECLARE @MainHospital varchar(50)='HOSPITAL 1';

SELECT 
    mainhospital, 
    COUNT([chkInpatient]) AS 'Inpatient Count', 
    COUNT([chkPartB]) AS 'PartB Count', 
    COUNT([chkOutpatient]) AS 'Outpatient Count', 
    COUNT([chkER]) AS 'ER Count'
FROM 
    SurveyPicList
WHERE 
    MainHospital = @MainHospital 
    AND chkInpatient = 'on' 
    AND chkPartB = 'on' 
    AND chkOutpatient = 'on' 
    AND chkER = 'on'
GROUP BY 
    MainHospital

2 个答案:

答案 0 :(得分:1)

您似乎想要单独计算每列。使用条件聚合,而不是where子句:

DECLARE @MainHospital varchar(50)='HOSPITAL 1';

SELECT mainhospital,
       SUM(CASE WHEN [chkInpatient] = 'on' THEN 1 ELSE 0 END) as "Inpatient Count",
       SUM(CASE WHEN [chkPartB] = 'on' THEN 1 ELSE 0 END) as 'PartB Count',
       SUM(CASE WHEN [chkOutpatient] = 'on' THEN 1 ELSE 0 END) as "Outpatient Count",
       SUM(CASE WHEN [chkER] = 'on' THEN 1 ELSE 0 END) as "ER Count"
FROM SurveyPicList
WHERE MainHospital = @MainHospital
GROUP BY MainHospital;

您的查询无效的原因是没有行将所有四列设置为on,这是您在where子句中所要求的。

请注意,我还更改了列别名以使用双引号。仅对字符串和日期常量使用单引号。

答案 1 :(得分:0)

您的第二个查询是查找chkInpatient,chkPartB,chkOutpatient和chkER都在' on' 每个记录。这就是为什么你没有收到任何记录?