计算MySQL在特定日期范围内每行值的百分比

时间:2018-04-02 22:46:18

标签: mysql

我想获取mysql数据库中某个表的某个日期范围内具有最高值的前4行。所以我可以用这个代码行来做,例如:

SELECT MONTH(date) as month, amount from sales where date >='2014-01-01' AND date <='2014-12-31' ORDER BY amount DESC LIMIT 4

但我想添加一个新列,其中包含每个值的百分比,我尝试使用此行:

SELECT MONTH(date) as month, amount, round(amount*100/sum(amount) ,1) as 'percent' from sales where date >='2014-01-01' AND date <='2014-12-31' ORDER BY `amount` DESC LIMIT 4

但它不起作用。我怎么才能得到它?我想要一些帮助。

1 个答案:

答案 0 :(得分:1)

这是一种做法。提供原始数据的片段也有帮助。创建sql fiddle有助于实现更多目标!!

select month, amount, round(amount*100/total,1) as percent
  from 
  (
    select MONTH(date) as month, amount 
      from sales 
      where date >='2014-01-01' AND date <='2014-12-31'
     ORDER BY amount DESC LIMIT 4
  ) c JOIN (
    select sum(amount) as total
      from sales 
      where date >='2014-01-01' AND date <='2014-12-31'
  ) t