MySQL:每周和每月平均值

时间:2016-03-14 09:57:07

标签: mysql sql database

这是我的帐单表:

shop_id | billing_date | total
------------------------------
ABC     | 2016-03-07   | 100
ABC     | 2016-03-14   | 200
DEF     | 2016-03-07   | 300
DEF     | 2016-03-14   | 100
GHI     | 2016-03-07   | 30

我希望每个商店获得一行,每周平均总数当前月总数,以及每月平均总数 。最终数据必须如下所示:

shop | weekly avg. | current month total | monthly avg.
-------------------------------------------------------
ABC  | 150         | 300                 | 300
DEF  | 200         | 500                 | 500
GHI  | 30          | 30                  | 30

我的问题是:是否可以直接从SQL查询中获取此信息?

3 个答案:

答案 0 :(得分:1)

嘿,您可以使用mysql的WEEKMONTH以当前年份的方式尝试这种方式。根据你的数据条目表是明智的:

SQLFIDDLE

select shop_id,(sum(total)/(WEEK(MAX(bdate)) - WEEK(MIN(bdate))+1)) as weekly_avg,(sum(total)/(MONTH(MAX(bdate))-MONTH(MIN(bdate))+1)) as mothly_avg, sum( case when MONTH(bdate) = MONTH(NOW()) then total else 0 end) as current_month_total  from bill group by shop_id WHERE YEAR(bdate) = 2016

年份大于一年

SQL FIDDLE

select shop_id,
sum(total)/(12 * (YEAR(MAX(bdate)) - YEAR(MIN(bdate))) + (MONTH(MAX(bdate)) - MONTH(MIN(bdate)))+1) as month_avg,
sum(total)/(7 * (YEAR(MAX(bdate)) - YEAR(MIN(bdate))) + (WEEK(MAX(bdate)) - WEEK(MIN(bdate)))+1) as weekly_avg,
sum( case when YEAR(bdate) = YEAR(bdate) and MONTH(bdate) = MONTH(NOW()) then total else 0 end) as current_month_total from bill group by shop_id

答案 1 :(得分:0)

这是你想要的事情吗?:

SELECT DISTINCT(bill.shop_id),wk as WeeklyTotal,mt as MonthlyTotal,ma as MonthlyAverage
FROM bill
JOIN (SELECT AVG(total) wk,shop_id
    FROM bill
    WHERE YEAR(billing_date) = 2016 AND MONTH(billing_date) = 1
    GROUP BY shop_id) as weekly ON bill.shop_id = weekly.shop_id
JOIN (SELECT SUM(total) mt,shop_id
    FROM bill
    WHERE YEAR(billing_date) = 2016 AND MONTH(billing_date) = 1
    GROUP BY CONCAT(shop_id,MONTH(billing_date))
    ) month_total ON month_total.shop_id = bill.shop_id
JOIN (SELECT AVG(total) ma,shop_id
    FROM bill
    WHERE YEAR(billing_date) = 2016 AND MONTH(billing_date) = 1
    GROUP BY CONCAT(shop_id,MONTH(billing_date))
) month_avg ON month_avg.shop_id = bill.shop_id

答案 2 :(得分:0)

您可以使用条件聚合和条件逻辑来执行此操作:

select shop_id,
       sum(total) / (7 * datediff(max(billing_date), min(billing_date)) + 1) as avg_weekly,
       sum(case when year(billing_date) = year(now()) and month(billing_date) = month(now()) then total else 0 end) as curr_Month,
       (sum(total) /
        (year(max(billing_date)) * 12 + month(max(billing_date)) - 
         year(min(billing_date)) * 12 + month(min(billing_date))
             ) + 1
        )
       ) as avg_month
total else 0 end) as week_total
from bill
gropu by shop_id;