简体   繁体   English

MySQL COUNT()GROUP BY子查询(?)可以计算每月在多个项目上的购买

[英]MySQL COUNT() GROUP BY subquery(?) to count purchases on multiple items per month

I'm using MySQL and i'd like to count the number of purchases of multiple items by the month in which each item was purchased. 我正在使用MySQL,我想按购买每个项目的月份计算购买多个项目的次数。 My table is called "items_purchased", the items are listed by "item_id", and the purchase date is a timestamp called "purchase_date". 我的表称为“ items_purchased”,项目由“ item_id”列出,购买日期是一个称为“ purchase_date”的时间戳。

here's my query so far: 到目前为止,这是我的查询:

SELECT items_purchased.item_id, items_purchased.purchase_date, 
DATE_FORMAT(DATE(purchase_date), '%m %y') AS monthYear FROM items_purchased 

The results in plain english would be something like this: 用简单的英语显示的结果将是这样的:

item_id=3: 2 purchases in june 2011, 3 purchases in july 2011 item_id = 3:2011年6月购买2次,2011年7月购买3次
item_id=2: 1 purchase in june 2011, 7 purchases in july 2011 item_id = 2:2011年6月购买1次,2011年7月购买7次

any help to help me figure out how to do the appropriate COUNT() and/or GROUP BY statements (or whatever else i may need) to determine the per month purchases for each item_id would be greatly appreciated! 任何帮助我找出如何执行适当的COUNT()和/或GROUP BY语句(或我可能需要的其他方法)来确定每个item_id每月购买量的帮助将不胜感激!

thank you, tim 蒂姆,谢谢你

SELECT YEAR(purchase_date) as year, DATE_FORMAT(purchase_date, '%M') as month, COUNT(item_id) as cnt
FROM items_purchased
GROUP BY YEAR(purchase_date), MONTH(purchase_date)
ORDER BY year, month, cnt

If you want per-itemID counts, add 'item_id' to the end of the GROUP BY clause. 如果要按项目ID计数,请在GROUP BY子句的末尾添加“ item_id”。 This'll just count how many itemIDs show up in any given year/month, but not break it down per-item. 这只会计算在给定的年份/月份中出现了多少itemID,但不会按项目细分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM