计算月份数字

时间:2017-10-20 04:43:19

标签: mysql sql database

我搜索并找到了解决方案,但他们没有使用MySQL,因为他们使用了其他软件的功能。

我试图显示本年度(1月份开始)的逐月增长,但知道如何在过去一年内检查也可能会在将来派上用场。

“订单”表格可能是什么样的:

+-----------+-------+
|   Month   | Sales |
+-----------+-------+
| 1-1-2017  |     3 |
| 1-5-2017  |     9 |
| 2-16-2017 |    10 |
| 2-16-2017 |    13 |
| 3-7-2017  |    25 |
| 4-29-2017 |    22 |
+-----------+-------+

我希望查询结果如下:

+----------+-------+--------+
|  Month   | Sales | Growth |
+----------+-------+--------+
| January  |    12 |        |
| February |    23 | 91.66% |
| March    |    25 | 8.69%  |
| April    |    22 | -12%   |
+----------+-------+--------+

有一种简单的方法吗?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

SELECT
  thisMonth.MonthOnly,
  SUM(thisMonth.Sales) AS ThisMonthSales,
  (SUM(thisMonth.Sales) / SUM(lastMonth.Sales) - 1) * 100 AS Growth
FROM
  (
    SELECT STR_TO_DATE(DATE_FORMAT(Month, '%Y%m01'), '%Y%m%d') AS MonthOnly,
    SUM(Sales) AS Sales
    FROM orders
    GROUP BY DATE_FORMAT(Month, '%Y%m01')
  ) thisMonth
  LEFT OUTER JOIN 
  (
    SELECT STR_TO_DATE(DATE_FORMAT(DATE_ADD(Month, INTERVAL 1 MONTH), '%Y%m01'), '%Y%m%d') AS MonthOnly,
    SUM(Sales) AS Sales
    FROM orders
    GROUP BY DATE_FORMAT(Month, '%Y%m01')
  ) lastMonth
  ON thisMonth.MonthOnly = lastMonth.MonthOnly
GROUP BY thisMonth.MonthOnly