我正在尝试通过Company_Name总结每个Wing_Name的每个雇员(总数)和QA_Score(平均)的Date_Time的最后值,并使用以下数据集:
+--------------+-----------+------------------+-----------+----------+
| Company_Name | Wing_Name | Date_Time | Employees | QA_Score |
+--------------+-----------+------------------+-----------+----------+
| Company A | Wing A | 06/08/2018 13:00 | 82 | 3.5 |
| Company A | Wing A | 06/08/2018 13:01 | 83 | 3.6 |
| Company A | Wing A | 06/08/2018 13:02 | 84 | 3.7 |
| Company A | Wing B | 06/08/2018 13:00 | 50 | 4.1 |
| Company A | Wing B | 06/08/2018 13:01 | 51 | 4.2 |
| Company A | Wing B | 06/08/2018 13:02 | 52 | 4.3 |
| Company B | Wing A | 06/08/2018 14:00 | 82 | 3.6 |
| Company B | Wing A | 06/08/2018 14:01 | 85 | 3.7 |
| Company B | Wing A | 06/08/2018 14:02 | 88 | 3.8 |
+--------------+-----------+------------------+-----------+----------+
所需的输出是:
+--------------+-----------+----------+
| Company_Name | Employees | QA_Score |
+--------------+-----------+----------+
| Company A | 136 | 4 |
| Company B | 88 | 3.8 |
+--------------+-----------+----------+
我已经成功地使用以下代码显示了Wing_Name的Date_Time的最后结果,但是我一生都无法为Company_Name找出它,而将Wing_Name排除在输出之外。
SELECT * FROM table
WHERE (Wing_Name, Date_Time) IN
(SELECT Wing_Name, MAX(Date_Time) Date_Time FROM table GROUP BY Wing_Name)
AND `Company_Name` = "Company A";
现在期望的输出应该是每个Wing_name的结果中Company_Name雇员的总和,以及相应Wing_Name的QA_Score的平均值,但汇总在Company_Name下
所需的输出遵循以下逻辑:
这一定是我所缺少的简单东西吗? 预先谢谢你。
答案 0 :(得分:1)
您需要在子查询中对company_name
和wing_name
进行分组,然后仅对company_name
进行主查询分组,以合并所选的行。
SELECT t1.company_name, SUM(t1.employees) AS employees, AVG(t1.qa_score) AS qa_score
FROM table AS t1
JOIN (SELECT company_name, wing_name, MAX(date_time) AS maxtime
FROM table
GROUP BY company_name, wing_name) AS t2
ON t1.company_name = t2.company_name AND t1.wing_name = t2.wing_name AND t1.date_time = t2.maxtime
GROUP BY t1.company_name