日期:2014-05-17  浏览次数:20591 次

sql server 2012统计
表A

name    quantity
a       1
b       2
c       7

需要统计结果

name    quantity    百分比
a        1          10% 
b        2          20% 
c        7          70%  

谢谢
------最佳解决方案--------------------
WITH test (name ,   quantity)
 AS 
 (SELECT 'a',       1
 UNION ALL 
 SELECT 'b',       2
 UNION ALL 
 SELECT 'c',       7)
 SELECT NAME,quantity,CONVERT(VARCHAR(10),CONVERT(FLOAT(5),quantity)/(select SUM(quantity)total FROM test)*100)+'%'
 FROM test 
 /*
 NAME quantity    
 ---- ----------- -----------
 a    1           10%
 b    2           20%
 c    7           70%
 
 (3 行受影响)
 
 
 */

------其他解决方案--------------------
select name,quantity,cast(quantity/(select SUM(quantity) from A)*100 as varchar(10))+'%'
from A
------其他解决方案--------------------
没用过,但是光这个问题,没必要group 哦
------其他解决方案--------------------
Select T.Name,T.Qty,Cast(T.Qty/x.Qty*100 as varchar(10))+'%' as Perc
 From _Tab T,(Select Sum(Qty) as Qty From _Tab) x

------其他解决方案--------------------
引用:
select name,quantity,cast(quantity/(select SUM(quantity) from A)*100 as varchar(10))+'%'
from A


这种方法我会,我是想能不能用rollup 或者其它的方法来统计。
------其他解决方案--------------------
引用:
SQL code?1234567891011121314151617181920WITH test (name ,   quantity) AS  (SELECT 'a',       1 UNION ALL  SELECT 'b',       2 UNION ALL  SELECT 'c',       7) SELECT NAME,quantity,CONVERT(……



能用rollup这种统计吗?
------其他解决方案--------------------
那就同求吧  。。。