如何平均行?

时间:2019-07-14 14:05:36

标签: mysql sql

我有该主题标题的表,另一个包含答复(每个主题)

如何获得每个主题的平均回复数(总计)?

tkts_topics

id  open_by     status
12  4             3
2   2             3


tkts_replies

id  tkt_id  open_by     name    text
2    2       2          asaf    some text

2 个答案:

答案 0 :(得分:1)

您只需要将两个表中的计数相除即可。

select ( (select count(*) from tkts_replies) /
         (select count(*) from tkts_topics)
       ) as avg_replies_per_topic

答案 1 :(得分:0)

加入表格并按主题ID分组以获得每个主题的回复数。
然后获取所有这些数字的平均值:

select avg(g.counter) averagereplies from (
  select count(r.id) counter
  from tkts_topics t left join tkts_replies r
  on r.tkt_id = t.id 
  where t.status = 3
  group by t.id 
) g

请参见demo

相关问题