mysql 查询月度同环比
时间: 2023-10-05 19:08:28 浏览: 117
查询月度同环比的 SQL 语句如下:
```sql
SELECT
DATE_FORMAT(date, '%Y-%m') AS month,
SUM(IF(DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH, '%Y-%m'), amount, 0)) AS last_month,
SUM(IF(DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(CURDATE() - INTERVAL 12 MONTH, '%Y-%m'), amount, 0)) AS last_year,
SUM(amount) AS current_month,
ROUND((SUM(amount) - SUM(IF(DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH, '%Y-%m'), amount, 0))) / SUM(IF(DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH, '%Y-%m'), amount, 0)), 2) AS mom,
ROUND((SUM(amount) - SUM(IF(DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(CURDATE() - INTERVAL 12 MONTH, '%Y-%m'), amount, 0))) / SUM(IF(DATE_FORMAT(date, '%Y-%m') = DATE_FORMAT(CURDATE() - INTERVAL 12 MONTH, '%Y-%m'), amount, 0)), 2) AS yoy
FROM
table_name
WHERE
DATE_FORMAT(date, '%Y-%m') BETWEEN DATE_FORMAT(CURDATE() - INTERVAL 12 MONTH, '%Y-%m') AND DATE_FORMAT(CURDATE(), '%Y-%m')
GROUP BY
DATE_FORMAT(date, '%Y-%m')
```
解释:
1. 使用 `DATE_FORMAT` 函数将日期格式化为年月格式;
2. 使用 `SUM` 函数计算每个月的总金额;
3. 使用 `IF` 函数过滤出上个月和去年同月的金额;
4. 计算月度同比和环比,使用 `ROUND` 函数保留两位小数;
5. 使用 `GROUP BY` 按月份分组。
其中,`table_name` 为表名,`date` 为日期列名,`amount` 为金额列名。
阅读全文