查找与上一年相比的百分比增长

时间:2018-04-21 16:32:19

标签: mysql

说实话,我不知道从哪个脚本开始。我可以从销售表中产生每月显示销售总收入的结果。

以下脚本:

SELECT coalesce(date_format(TRANSACTION_DATE, '%M'), 'Grand Total') AS MONTH,
ROUND(SUM(SALES_AMOUNT),2) TOTAL
FROM SALES
WHERE YEAR(TRANSACTION_DATE) = 2018
GROUP BY month

结果:(这很好,并且能够正常运作)

Month   Total
January 45163.22
February    34531.15
March   44194.98
April   30826.68
May 39016.04
June    37284.25
July    37640.08
August  39703.85
September   34958.94
October 34447.61
November    39161.9
December    36986.16

但是,我想产生以下结果......即Jan为NULL,而2月差为-10632.07,等于减少23.54%

        Difference  Percentage Increase/Decrease
January 45163.22        
February    34531.15    -10632.07   -23.54
March   44194.98    9663.83 27.99
April   30826.68    -13368.3    -30.25
May 39016.04    8189.36 26.57
June    37284.25    -1731.79    -4.44
July    37640.08    355.83  0.95
August  39703.85    2063.77 5.48
September   34958.94    -4744.91    -11.95
October 34447.61    -511.33 -1.46
November    39161.9 4714.29 13.69
December    36986.16    -2175.74    -5.56

希望这是有道理的,如果有人能帮助我,那就太棒了。

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用联接

import os 
temp = input("Please Enter File Name to create: ")
FileName = open(temp,"w+")
print("File Created!"+"\n")
FileName.close() # <---

temp = input("Please Enter File Name to delete: ")
os.remove(temp)
print("File Removed!)

答案 1 :(得分:0)

通过在本月加入SALES,并将第二次销售限制在上一年,您将获得两年的匹配月份。

SELECT 
    coalesce(date_format(a.`TRANSACTION_DATE`, '%M'), 'Grand Total') AS `MONTH`,
    ROUND(SUM(a.`SALES_AMOUNT`),2) AS `TOTAL_2018`,
    ROUND(SUM(b.`SALES_AMOUNT`),2) AS `TOTAL_2017`,
    ROUND(SUM(a.`SALES_AMOUNT`),2) - ROUND(SUM(b.`SALES_AMOUNT`),2) AS `Difference`,
    ROUND((ROUND(SUM(a.`SALES_AMOUNT`),2) - ROUND(SUM(b.`SALES_AMOUNT`),2)) / ROUND(SUM(b.`SALES_AMOUNT`),2),2) AS `Percentage_Difference`
FROM `SALES` a
JOIN `SALES` b
ON YEAR(b.`TRANSACTION_DATE`) = YEAR(a.`TRANSACTION_DATE`) - 1 AND 
    MONTH(a.`TRANSACTION_DATE`) = MONTH(b.`TRANSACTION_DATE`)
WHERE YEAR(a.`TRANSACTION_DATE`) = 2018
GROUP BY a.coalesce(date_format(a.`TRANSACTION_DATE`, '%M'), 'Grand Total')
ORDER BY a.coalesce(date_format(a.`TRANSACTION_DATE`, '%M'), 'Grand Total');

请注意,通过删除WHERE子句并将年份添加到group by和order by子句,您可以生成多年的报告。