我有一个查询,将本月的数字与上个月和上个月进行比较。唯一的问题是同事抱怨标签。
我上个月使用M1 = M2 =上月,但有些人仍然把它混淆了。我想在实际的月份而不是M1,M2等等。任何想法都会有帮助。这是我的代码
SELECT *,
CONCAT(FORMAT((current_downloads/M_1)*100,2),'%') AS `M_1_Ratio`,
CONCAT(FORMAT((current_downloads/M_2)*100,2),'%') AS `M_2_Ratio`
FROM
(SELECT count(*) AS current_downloads
FROM `purchase`
WHERE date(`purchase`.`timestamp`) >= DATE_FORMAT(NOW() ,'%Y-%m-01')) t1
JOIN
(SELECT count(*) AS M_1
FROM `purchase`
WHERE date(`purchase`.`timestamp`) BETWEEN DATE_SUB(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL 1 MONTH) AND DATE_SUB(DATE(NOW()), INTERVAL 1 MONTH)) t2
JOIN
(SELECT count(*) AS M_2
FROM `purchase`
WHERE date(`purchase`.`timestamp`) BETWEEN DATE_SUB(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL 2 MONTH) AND DATE_SUB(DATE(NOW()), INTERVAL 2 MONTH)) t3
这就是这样的。
我需要标题名称为实际月份。
答案 0 :(得分:0)
这是一个可怕的黑客攻击(只有在你的输出完全用于演示时才会起作用),但你可以使用UNION
向表中添加另一行数据,其中包括月份名称:
SELECT DATE_FORMAT(NOW(), '%b %y') as Current_Downloads, DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%b %y') as M_1, DATE_FORMAT(NOW() - INTERVAL 2 MONTH, '%b %y') as M_2, DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%b %y') as M_1_Ratio, DATE_FORMAT(NOW() - INTERVAL 2 MONTH, '%b %y') as M_2_Ratio
UNION ALL
... your query ...
这会给你一些看起来像这样的东西:
Current Downloads M_1 M_2 M_1_Ratio M_2_Ratio
Mar 18 Feb 18 Jan 18 Feb 18 Jan 18
12,168 12,121 13,345 100.39% 91.18%