按星期几记录订单值

时间:2019-05-04 04:34:47

标签: mysql mysqli

我正在尝试根据星期几来获取记录订单值,该表格基于具有以下列的表:

id
amount
date

我想知道在MySQL中是否有一种简便的方法?

我正在考虑按天对金额进行分组,然后按一周中的天对天进行分组,然后仅检索最高值。我不确定这是否是最好的解决方法。

1 个答案:

答案 0 :(得分:1)

这应该做您想要的;它会找到一周中每一天的最大总数,然后JOIN将其与每一天的总数相乘,以找出每个工作日出现最大值的那一天:

SELECT t.weekday, t.date, t.total
FROM (SELECT date, DATE_FORMAT(date, '%W') AS weekday, SUM(amount) AS total
      FROM yourtable
      GROUP BY date) t
JOIN (SELECT DATE_FORMAT(date, '%W') AS weekday, MAX(total) AS max_total
      FROM (SELECT date, SUM(amount) AS total
            FROM yourtable
            GROUP BY date) t
      GROUP BY weekday) w ON w.weekday = t.weekday AND w.max_total = t.total

输出(用于我的演示)

weekday     date        total
Thursday    2019-04-11  110.00
Friday      2019-04-12  100.00
Saturday    2019-04-20  180.00
Sunday      2019-04-21  50.00
Monday      2019-04-22  160.00
Tuesday     2019-04-23  50.00
Wednesday   2019-04-24  230.00

Demo on dbfiddle