您的位置:首页 > 数据库

一条SQL语句统计百分比

2011-10-12 17:06 211 查看
一条很简单的语句查询百分比

本例是查询文章是被点击过的在点所有文章的比重

select CONVERT(decimal(2,2),
100 * convert(float, sum( case viewcount when 0 then 0 else 1 end))
/ convert(float,(case COUNT(id) when null then 1 else (case COUNT(id) when 0 then 1 else count(id) end) end))
)
from Article


程序释义如下:

   (case COUNT(id) when null then 1 else (case COUNT(id) when 0 then 1 else count(id) end) end) ——统计所有文章的数量,如果所有文章的数量为0或者为null计为1,因为分母不能为0

  convert(float, sum( case viewcount when 0 then 0 else 1 end)) ——统计访问量大于1的文章,实现思路是求所有被访问过的文章的和,在Sum()函数中如果文章访问量大于0则加1,反之则加0, 如果最后数量为null,则计为0

   因为整数除以整数,会略去小数部分,所以会把统计出来的两个量,转化为Float类型,

  最近,将结果格式化为小数点后有两位的小数,

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql float null