2016-04-06 51 views
0

在SQL Server中,我有一個EventDate和Attended的簡單表,其中Attended包含5個值中的1個(出席,取消,未出席,其他,未知)。我需要一個返回未知數的速率的查詢。我不關心其他價值的比率。計算給定字段值的速率(SQL Server)

我知道我可以使用where子句返回Attended的值爲'Unknown'的記錄數,但是我最終需要最終達到總數的百分比,最好是在一個查詢中。

這個查詢獲得了未知數的總和,但我從哪裏去得到未知數的百分比?

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

提示:總共有11300行,其中值爲Unknown的值爲2212。我想返回0.195查詢(這是一萬一千三百分之二千二百十二= 19.5%)

回答

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 
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