If you just想要查看基于标签的徽章并且不关心其余的,您可以将测试移至 where 子句:
select count(*)
from Badges
where TagBased = 1
规范的解决方案是将位值转换为可以求和的数据类型:
select sum(cast(TagBased as decimal))
from Badges
一个更灵活的解决方案是自己进行转换案例陈述 https://msdn.microsoft.com/en-us/library/ms181765.aspx:
select sum(case TagBased when 1 then 100.0 end)/count(*) tag_based_per
from Badges
或者,在较新版本的 SQL Server 中,有一个IIF函数 https://msdn.microsoft.com/en-us/library/hh213574.aspx:
select sum(iif(TagBased = 1, 1, 0))
from Badges
最后,如果你正在打高尔夫球,你可以欺骗 SQL 来为你转换位:
select sum(TagBased+0)
from Badges
这项技术的功劳在于肯尼思·巴尔特里尼克 https://stackoverflow.com/a/4503685/1438对一个更具体问题的回答。
供参考(和潜在的分叉):我的测试查询 https://data.stackexchange.com/stackoverflow/query/356002/how-many-tag-badges-have-been-awarded?opt.textResults=true.