MySQL 获取按月分组的过去 12 个月的数量

编程入门 行业动态 更新时间:2024-10-28 04:26:57
本文介绍了MySQL 获取按月分组的过去 12 个月的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试用 PHP 编写 MySQL SELECT 语句.

I'm trying to write a MySQL SELECT statement in PHP.

我有 2 个表,sales 和 sale_items.

I have 2 tables, sales and sale_items.

sales 有列:sale_id、status

sale_items 有列:sale_id、date_ added (DATETIME)、quantity

sale_items has columns: sale_id, date_added (DATETIME), quantity

我需要从 sale_items 返回过去 12 个月按月分组的数量以及 sales 等于已完成"(如您所见,sales 和 sale_items 可以由 sale_id 连接).

I need to return the quantities from sale_items, over the last 12 months grouped by month and where the status of the corresponding row in sales is equal to 'completed' (as you can see, sales and sale_items can be joined by sale_id).

我尝试修改以下两个以满足我的需要,但没有运气:

I have tried modifying both of the following to suit my needs, but with no luck:

MySQL 每月销售最后一个12 个月,包括没有销售的月份

过去 12 个月的 Mysql 总和

推荐答案

使用 MySQL 非常简单 MONTH() 函数以及GROUP BY caluse.

It's very easy you can use MySQL MONTH() function for this along with GROUP BY caluse.

SELECT SUM(SI.quantity),MONTH(SI.date_added) FROM sale_items SI JOIN sales S ON S.id=SI.sale_id WHERE S.status = 'completed' GROUP BY MONTH(SI.date_added);

更多推荐

MySQL 获取按月分组的过去 12 个月的数量

本文发布于:2023-10-21 17:03:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1514819.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:个月   按月   数量   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!