我想计算上一年的增长百分比。
表格结构:
CustomerName | Sum_1415 | Sum_1516
我试过这个问题:
select CustomerName, SUM(Sum_1415), SUM(Sum_1516),
round(sum(Sum_1516)-Sum(Sum_1415)/(select sum(Sum_1415) from dummy),2) as Percentage
from dummy
group by CustomerName
order by Sum_1415 desc
limit 15
答案 0 :(得分:1)
仅使用(select sum(Sum_1415) from dummy)
替换子查询sum(Sum_1415)
。否则,您需要计算每个客户的增长率与上一年度所有收入的总和,而不是该客户的总数。
在ROUND
调用中,您还在减法sum(Sum_1516)-Sum(Sum_1415)
周围丢失了一些括号。
select CustomerName, SUM(Sum_1415) AS Sum_1415, SUM(Sum_1516) AS Sum_1516,
round((sum(Sum_1516)-Sum(Sum_1415))/SUM(Sum_1415),2) as Percentage
from dummy
group by CustomerName
order by Sum_1415 desc
limit 15
我可能会将其重构为子查询,因此没有必要继续重复SUM
表达式。
SELECT CustomerName, Sum_1415, Sum_1516, ROUND((Sum_1516-Sum_1415)/Sum_1415, 2) AS Percentage
FROM (SELECT CustomerName, SUM(Sum_1415) AS Sum_1415, SUM(Sum_1516) AS Sum_1516
FROM dummy
GROUP BY CustomerName
ORDER BY Sum_1516 DESC
LIMIT 15) AS x