SQL中同一列的百分比

时间:2015-02-10 09:05:16

标签: sql sql-server

我需要计算SQL中的总百分比 我有

  

customerID,数量

我所尝试的是:

SELECT 
   customer_id, 
   sum(quantity) / (quantity * 100)
FROM MyTable
Group by customer_id

6 个答案:

答案 0 :(得分:3)

您需要总计来计算百分比,因此请使用子查询。为避免为每个用户重复计算总数,请将交叉连接计算为计算一次的总数:

select customer_id, quantity * 100 / total
from MyTable 
cross join (
    select sum(quantity) total
    from MyTable) x

答案 1 :(得分:1)

您需要先获得总数量才能计算客户数量百分比。

DECLARE @TotalQty int
set @TotalQty = (select sum(Amount) FROM tbltemp)    
SELECT id, Amount * 100 / @TotalQty  FROM tbltemp 

答案 2 :(得分:1)

尝试fiddle

之类的内容
SELECT customer_id, (sum(quantity) / count(quantity ) * 100)
FROM MyTable 
Group by customer_id

答案 3 :(得分:1)

最有效的方法是使用sum () over。试试这个。

SELECT 
   customer_id, 
   (quantity * 100)/sum(quantity) over() 
FROM MyTable

答案 4 :(得分:1)

只需使用子选择:

Select customer_id, quantity, quantity / sum(quantity) * 100 per
From
(SELECT customer_id, 
   sum(quantity) quantity
FROM MyTable
Group by customer_id) a

答案 5 :(得分:0)

DECLARE @TotalQty int
SET @TotalQty = (SELECT SUM(Amount) FROM tbltemp)    
SELECT id, Amount * 100 / @TotalQty  FROM tbltemp