mysql分组平均,mysql分组平均计算

id originator revenue date

1 acme 1 2013-09-15

2 acme 0 2013-09-15

3 acme 4 2013-09-14

4 acme 6 2013-09-13

5 acme -6 2013-09-13

6 hello 1 2013-09-15

7 hello 0 2013-09-14

8 hello 2 2013-09-13

9 hello 5 2013-09-14

I have the above table . And I would like to add the ranking column based on the revenue generated by the originator based on the revenue for last 3 days

the fields to be displayed as below:

originator revenue toprank

hello 8 1

acme 5 2

2) And based on the above data , i would like to calculate the avg revenue generated based on the following criteria

If the sum of total revenue for the same date is 0 ( zero) then it should not be counted with calculating the average.

a) avg value for originator acme should be sum of revenue/count(no of dates where the revenue is non zero value) so (4+1)/2 i.e 2.5

b) avg value for originator hello should be sum of revenue/count(no of dates where the revenue is non zero value) so (5+2+1)/3 i.e 2.6666

originator revenue toprank avg(3 days)

hello 8 1 2.6666

acme 5 2 2.5

解决方案

You first need to group the records by date in order to find the daily totals and exclude those days that have a total sum of zero.

Then use that query as a subquery from which you group again to get the totals and averages by originator.

Finally, perform the ranking (either in your application code as you loop over the resultset, or else in MySQL using an outer query with user variables).

SELECT originator, revenue, @r:=@r+1 AS toprank, avg FROM (

SELECT originator, SUM(total) AS revenue, AVG(total) AS avg

FROM (

SELECT originator, date, SUM(revenue) AS total

FROM my_table

-- WHERE date BETWEEN CURRENT_DATE - INTERVAL 3 DAY AND CURRENT_DATE

GROUP BY originator, date

HAVING total <> 0

) t

GROUP BY originator

ORDER BY revenue DESC

) t, (SELECT @r:=0) init

See it on sqlfiddle.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值