计算给定字段值的速率(SQL Server)

时间:2016-04-06 16:35:28

标签: sql-server

在SQL Server中,我有一个带有EventDate和Attended的简单表,其中Attended包含5个值中的1个(出席,取消,未出席,其他,未知)。我需要一个返回未知数的RATE的查询。我不关心其他价值的比率。

我知道我可以使用where子句返回Attended值为“未知”的记录数,但我需要最终得出总数的百分比,最好是在一个查询中。

此查询获取未知数的总和,但是我从哪里获取未知数的百分比?

SELECT Count(Attended) As TotalCount
FROM [MyTable]
WHERE (Attended = 'Unknown')
AND Month(EventDate) = 1
AND Year(EventDate) = 2016
GROUP BY Attended

提示:总共有11300行,其中2212是值未知。我想要一个返回.195(2212/11300 = 19.5%)的查询

2 个答案:

答案 0 :(得分:1)

使用条件COUNT()

SELECT COUNT( CASE WHEN Attended = 'Unknown' THEN 1 END ) * 100.0 
           /
       COUNT(*) As UnknowRate
FROM [MyTable]
WHERE Month(EventDate) = 1
  AND Year(EventDate) = 2016

答案 1 :(得分:0)

您可以使用CASE语句执行“条件计数”,如下所示:

select 
    count(*) as TotalCount,
    sum(case when Attended = 'Unknown' then 1 else 0 end) as AttendedUnknownCount,
    cast(sum(case when Attended = 'Unknown' then 1 else 0 end) as float)
    / cast(count(*) as float) as PctAttendedUnknown
from MyTable
Where Month(EventDate) = 1 and Year(EventDate) = 2016

请注意,由于您正在考虑所有行(不仅仅是“未知”行),因此您不必执行group by