在MYSQL中显示过去六个月中每个类别的总费用

时间:2017-08-26 07:49:34

标签: php mysql sql

请在标记为重复之前阅读

这是产品表的结构: Table products

此表中有超过600行记录。

我想要的是它显示的内容

| Category | Price | Month | Year  |
|  Bills   | 12389 |  08   | 2017  |
|  Food    | 10589 |  08   | 2017  |
|  ...     | ..... |  ..   | ....  |
|  Bills   | 18989 |  07   | 2017  |
|  Food    | 20589 |  07   | 2017  |
|  ...     | ..... |  ..   | ....  |
|  Bills   | 12784 |  06   | 2017  |
|  Food    | 23589 |  06   | 2017  |
|  ...     | ..... |  ..   | ....  |

我做了什么?

SELECT category AS 'Category', SUM(total_PRICE) AS 'Total Amount' 
FROM `products`
WHERE month(DATE)=(SELECT MONTH(CURDATE())) AND year(DATE)=(SELECT YEAR(CURDATE())) GROUP BY category  ORDER BY `Total Amount`  DESC

这一个返回当月的记录" 类别视图"

我也试过这个

SELECT *
FROM products
WHERE date_format(date,'%Y-%m') < date_format(now(),'%Y-%m') and
      date_format(date,'%Y-%m') >= date_format(now() - interval 6 month,'%Y-%m')

这将返回过去六个月的所有记录

如果无法编写此类查询,请帮我编写一个用PHP打印此类数据的程序

1 个答案:

答案 0 :(得分:1)

你似乎想要:

SELECT category, date_format(date,'%Y-%m') as yyyymm, SUM(total_PRICE)
FROM products
WHERE date_format(date,'%Y-%m') < date_format(now(),'%Y-%m') and
      date_format(date,'%Y-%m') >= date_format(now() - interval 6 month,'%Y-%m')
GROUP BY category, date_format(date,'%Y-%m')
ORDER BY category, yyyymm DESC;