简体   繁体   English

计算MySQL中每个项目的平均行数

[英]Calculate mean number of rows per item per month in MySQL

I had trouble finding a clear, generic way of phrasing this question, so apologies if it's a repeat. 我很难找到一种清晰,通用的措词表达方式,因此很抱歉,如果重复的话。 Here's the situation: 情况如下:

I have a table recording collaborative tagging data, with each row storing an annotation (ie a particular user tagging a particular item with a particular tag at a particular time). 我有一个记录协作标记数据的表,每行存储一个注释(即特定用户在特定时间用特定标记标记特定项目)。 Here's a sample for clarity: 为了清晰起见,下面是一个示例:

+---------+---------+--------+------------+
| user_id | item_id | tag_id | tag_month  |
+---------+---------+--------+------------+
| 1040740 |    2653 |   1344 | 2005-07-01 |
| 1040740 |    3602 |   1344 | 2005-07-01 |
| 1040740 |   17746 |    217 | 2005-07-01 |
| 1040740 |   21426 |   1344 | 2005-07-01 |
| 1040740 |   22224 |    180 | 2005-07-01 |
+---------+---------+--------+------------+

...and so on. ...等等。 What I'm trying to calculate is, on a month-by-month basis, the mean number of annotations per item, across all items. 我要计算的是每个月每个项目在所有项目中的平均注释数。 In other words, for each month, what is the average number of rows per unique item for that month? 换句话说,对于每个月,每个唯一项目在该月的平均行数是多少? My dataset spans 94 total months, so the output of the query I'm wanting should be 94 rows, each with average number of annotations per item for that month. 我的数据集总共超过94个月,因此我想要的查询的输出应该是94行,每行包含该月的每个项目的平均注释数。 Note that the "user_id" column is completely irrelevant to this. 注意,“ user_id”列与此完全无关。

I think you need just to do the corresponding COUNT's: 我想你只需要做相应的COUNT:

SELECT 
  COUNT(DISTINCT item_id),
  YEAR(tag_month),
  MONTH(tag_month)
FROM
  t
GROUP BY
  YEAR(tag_month),
  MONTH(tag_month)

not sure if you want to get item_id , but, if you need, then: 不确定是否要获取item_id ,但是,如果需要,则:

SELECT 
  COUNT(1),
  item_id,
  YEAR(tag_month),
  MONTH(tag_month)
FROM
  t
GROUP BY
  item_id,
  YEAR(tag_month),
  MONTH(tag_month)

Slight deviation to Alma Do Mundo's answer to give the average number of tags per item per month. 与Alma Do Mundo的答案略有偏差,给出每月每件商品的平均标签数量。

SELECT 
  COUNT(*) / COUNT(DISTINCT item_id) as tag_average,
  YEAR(tag_month),
  MONTH(tag_month)
FROM
  t
GROUP BY
  YEAR(tag_month),
  MONTH(tag_month)

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

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