如何在SELECT中获得没有大子查询的总销售额百分比

时间:2015-02-23 10:57:39

标签: mysql sql sql-server

我面临一个计算生产金额总计的方法的问题,所以我可以用它来计算 (用户销售额/总用户销售额)百分比

SELECT * FROM Sales

ID      Item    Amount
5       IS1     10.00
5       IS2     2.00
3       IS1     10.00
2       IS3     7.00
9       IS5     6.00

Example         35.00

DESIRED OUTPUT

ID      Amount  Percentage
5       12.00   34.28571%
3       10.00   28.57142%
2       7.00    20.00000%
9       6.00    17.14285%

Example 35.00   100.0000%

SELECT ID, SUM(Amount) AS Amount
FROM Sales
GROUP BY ID

我在堆栈和其他论坛上看到了各种例子,其中人们使用额外的选择来计算金额列的总数

SELECT ID, SUM(Amount) AS Amount,(SELECT SUM(Amount) FROM Sales) AS Total, Amount/(SELECT SUM(Amount) FROM Sales)*100 AS Percentage 
FROM Sales
GROUP BY ID

但是当我的选择查询很大时,我该怎么做,你还把它放在选择查询中还是有更好的方法可以做到这一点。

SELECT a.ID, SUM(a.Amount) AS Amount, @rank:=@rank + 1 AS rank
FROM Sales a
INNER JOIN (SELECT @rank:=0) r
WHERE a.Item='IS1' 
AND a.tdate='2015-01-20'
GROUP BY a.ID
ORDER BY Amount

原始查询实际上比这长,因为它还从其他表中提取描述和值。

基本上我正在做的原始代码将转到Sales表,按当前日期,按产品,按产品sub_id,按事务ID提取所有用户销售数据。然后排名谁在当天销售特定交易ID的最高产品数量。

当然这个代码变得很大,所以我不确定在SELECT查询中再次添加整个代码以计算总数是否正确?

没有办法,它可以在不进行其他查询的情况下计算总金额吗?

4 个答案:

答案 0 :(得分:0)

这适用于MSSQL,不确定MySQL

Select distinct ID, SUM(AMOUNT) OVER (PARTITION BY ID) Amount, SUM(AMOUNT) OVER (PARTITION BY ID) / SUM(AMOUNT) OVER (PARTITION BY 1) * 100 Percentage
from Sales 
order by ID

它为您提供了所需的输出,如上所示。

答案 1 :(得分:0)

如果它解决了我的问题,我会通过窗口函数来优先选择一个组:

SELECT a.ID, SUM(a.Amount) AS Amount, @rank:=@rank + 1 AS rank
  , s.SumAll Total
  , SUM(a.Amount)/s.SumAll*100 Percentage
FROM Sales a
, (SELECT @rank:=0) r
, (SELECT SUM(Amount) SumAll FROM Sales ) s
WHERE a.Item='IS1' 
AND a.tdate='2015-01-20'
GROUP BY a.ID
ORDER BY Amount

假设sales实际上是一个相当昂贵的视图,你可能会更好(假设mysql喜欢窗口函数):

SELECT a.ID, SUM(a.Amount) AS Amount
  , @rank:=@rank + 1 AS rank
  , SUM(Amount) OVER (Partition By 1) Total
  , SUM(a.Amount)/SUM(Amount) OVER (Partition By 1)*100 Percentage
FROM Sales a
, (SELECT @rank:=0) r
WHERE a.Item='IS1' 
AND a.tdate='2015-01-20'
GROUP BY a.ID
ORDER BY Amount

答案 2 :(得分:0)

declare @total_amt as decimal(18,5)
set @total_amt=(select sum(isnull(AMOUNT,0)) from Sales)
select Id,AMOUNT,(SUM(Amount)/(@total_amt)*100) as Percentage from Sales group by Id

答案 3 :(得分:0)

此查询产生所需的输出,而在MySQL中没有子查询。 总和(金额)() 为您提供总金额

SELECT ID, SUM(Amount) AS Amount,
       SUM(Amount)*100/SUM(Amount) OVER () AS percentage
FROM Sales
GROUP BY ID