select name,str((case (select isnull(sum(cost),0) from table1) when 0 then 0 else cost/(select isnull(sum(cost),0) from table1) end)*100,10,2)+'%' as bfb from table1
以上sql语句较长,解释一下:
使用case...when...end,是为了避免合计cost为0的话,出现无法除0的错误;结果值乘以100是为了配合百分比格式;使用str(...,10,2)函数是把计算出来的数字值转换成两位小数精度的文本串;最后,在结果后加上一个百分号,效果就完整了。
以上语句在sqlserver数据库中测试通过。
SELECT
(T2/T1.cost)/100 || ‘%’
FROM
(SELECT SUM(cost) As cost from table1) T1,
(SELECT SUM(cost)AS cost from table1
WHERE name = '张三') T2
select aaa.name,aaa.cost_s/bbb.cost_t 比例 from
(select name,cast (sum(cost) as float) cost_s from T group by name) aaa,
(select cast(sum(cost) as float) cost_t from T)
bbb
--where name='张三'
这里是所有人的统计 结果是小数 没有加百分号