我有一个表,其中包含汽车维修费用的记录,其中包括日期,金额和项目以及其他列。我需要比较每个项目每月的费用,我已经弄清楚了如何显示所有项目->一个月或一个项目->所有月份:
mysql> select rubros, format(sum(montos),2) from folios where month(fecha)='1' group by rubros;
+--------------------------------+-----------------------+
| rubros | format(sum(montos),2) |
+--------------------------------+-----------------------+
| ARTICULOS DE LAVADO | 215,621.83 |
| BATERIAS | 50,603.50 |
| ESTEREOS | 2,950.00 |
| FRENOS | 206,823.80 |
| LLAVES | 62,859.81 |
| REFACCIONES ACEITE Y LUBRICANT | 332,307.69 |
| SERVICIO MAYOR | 69,308.86 |
| SERVICIO MENOR | 177,395.90 |
+--------------------------------+-----------------------+
8 rows in set (0.07 sec)
mysql> select rubros, format(sum(montos),2) from folios where month(fecha)='2' group by rubros;
+--------------------------------+-----------------------+
| rubros | format(sum(montos),2) |
+--------------------------------+-----------------------+
| ARTICULOS DE LAVADO | 194,956.00 |
| BATERIAS | 92,426.99 |
| ESTEREOS | 8,952.13 |
| FRENOS | 177,075.45 |
| LLAVES | 53,170.73 |
| REFACCIONES ACEITE Y LUBRICANT | 325,269.06 |
| SERVICIO MAYOR | 69,593.19 |
| SERVICIO MENOR | 212,949.26 |
+--------------------------------+-----------------------+
8 rows in set (0.07 sec)
有没有办法像一张桌子一样显示所有项目->像下个月一样显示所有月份? :
| rubros | Month_1 | Month_2 | ...
+----------|-----------|-----------|----
| BATERIAS | 50,603.50 | 92,426.99 | ...
| ESTEREOS | 2950.00 | 8,952.13 | ...
|...
考虑到我每个月都有许多“ baterias”,“ frenos”,“ llaves” ...等等项目(这就是为什么我使用sum());我尝试了一些我发现的问题,但是我得到的最接近的结果是每个项目有1个查询,使用以下命令显示了所有月份的金额:
mysql> select rubros,
(select sum(montos) from folios where month(fecha)=1 and rubros = 'baterias') as Month_1,
(select sum(montos) from folios where month(fecha)=2 and rubros = 'baterias') as Month_2
from folios where rubros = 'baterias' group by rubros;
+----------+----------+----------+
| rubros | Month_1 | Month_2 |
+----------+----------+----------+
| BATERIAS | 50603.50 | 92426.99 |
+----------+----------+----------+
1 row in set (0.10 sec)
我需要类似↑的东西,但要显示所有“红宝石”物品