简体   繁体   English

Mysqli-使用平均,总和,两个表分组

[英]Mysqli - Using avg, sum, group by with two tables

I know the basics when it comes to mysqli queries, but I'm having trouble with the following: 我了解mysqli查询的基础知识,但遇到以下问题:

I have a large table called caseStatistics with the following columns: 我有一个名为caseStatistics的大表, 其中包含以下各列:

idSchool (id for school), timeReported (unix timestamp), timeRead (unix timestamp), timeSolved (unix timestamp) idSchool (学校ID), timeReported (unix时间戳), timeRead (unix时间戳), timeSolved (unix时间戳)

I have another large table called school with the following columns: 我还有另一个大表,称为school,其中包含以下各列:

idSchool (id for school), name (name of school) idSchool (学校的ID), 名称 (学校的名称)

From these two tables, I want to output the name of the school, total cases, the avarage time it has taken for operators to respond to a case (after it was reported), and the avarage time on how long it has taken to solve the case (after it was reported). 从这两个表中,我想输出学校的名称,总案件数,操作员响应案件所花费的平均时间(报告后)以及解决问题所需时间的平均时间。案件(在举报之后)。 I also need the results to be grouped by the school name. 我还需要将结果按学校名称分组。

So it should output something like this: 因此它应该输出如下内容:

Name : BlaBlaSchool 姓名 :BlaBlaSchool

Total cases : 49 宗数 :49

Avarage respond time : 2 hours 平均响应时间 :2小时

Avarage solve time : 16 hours 平均解决时间 :16小时

(For each school) (针对每所学校)

I don't need assistance with converting from unix to days, hours, minutes etc, only the mysqli query. 我不需要从Unix转换为几天,几小时,几分钟等的帮助,仅需要mysqli查询。 Any help is greatly appreciated, thank you! 任何帮助,不胜感激,谢谢!

All you need to do is add the functions into the column list in the select statement: 您需要做的就是将函数添加到select语句的列列表中:

SELECT
  s.`name`,
  COUNT(*) AS totalCases,
  AVG(cs.`timeRead` - cs.`timeReported`) AS avgRespond,
  AVG(cs.`timeSolved` - cs.`timeReported`) AS avgSolved
FROM `caseStatistics` AS cs
LEFT JOIN `school` AS s ON s.`idSchool` = cs.`idSchool`
GROUP BY s.`name`

You can use the HAVING keyword to narrow results using the aggregate values (similar to WHERE ). 您可以使用HAVING关键字来使用合计值来缩小结果(类似于WHERE )。 Also, make sure to check out: https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html 另外,请确保签出: https : //dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

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

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