我如何计算并显示上个月的增长或亏损百分比(比较上个月的数字,而不是上一年)。
即。 Jan是500,结果将是0%。然后,当2月份为150时,百分比损失为-70%,3月将显示-86.67,因为他们的结果仅为20(与150英镑相比)
+----------+------+------------+
| Month | Sale | Difference |
+----------+------+------------|
| January | 500 | |
| February | 150 | -70.00 |
| March | 20 | -86.67 |
| April | 250 | 1150.00 |
| May | 280 | 12.00 |
| June | 400 | 42.86 |
| July | 480 | 20.00 |
+----------+------+------------+
我的下面的脚本产生:(我只需要添加另一个百分比列
+----------+-------------------+
| MONTH | SUM(SALES_AMOUNT) |
+----------+-------------------+
| January | 500 |
| February | 150 |
| March | 20 |
| April | 250 |
| May | 280 |
| June | 400 |
| July | 480 |
+----------+-------------------+
SELECT coalesce(date_format(DATE_PURCHASED, '%M')) AS MONTH,
SUM(SALE_PRICE)
FROM SALE
WHERE YEAR(DATE_PURCHASED) = 2017
GROUP BY month
答案 0 :(得分:0)
您可能会在月份减去1的情况下将查询加入到自身中。然后您将一个月的总和与一行的最后一个月相加并计算百分比。类似于以下内容:
SELECT monthname(concat('1970-', lpad(A.MONTH, 2, '0'), '-01')) AS MONTH,
A.SALE_PRICE,
CASE
WHEN A.SALE_PRICE IS NULL
THEN NULL
WHEN B.SALE_PRICE IS NULL
THEN NULL
WHEN A.SALE_PRICE = 0
THEN NULL
ELSE
(B.SALE_PRICE / A.SALE_PRICE - 1) * 100
END AS PERCENTAGE
FROM (SELECT month(DATE_PURCHASED) AS MONTH,
sum(SALE_PRICE) AS SALE_PRICE,
FROM SALE
WHERE year(DATE_PURCHASED) = 2017
GROUP BY MONTH) A
LEFT JOIN (SELECT month(DATE_PURCHASED) AS MONTH,
sum(SALE_PRICE) AS SALE_PRICE,
FROM SALE
WHERE year(DATE_PURCHASED) = 2017
GROUP BY MONTH) B
ON A.MONTH - 1 = B.MONTH
ORDER BY A.MONTH;
注意A
和B
是您的查询,只需修改以便月份为数字,因为ON
子句需要这样。