表如下:
MariaDB [test]> select * from AdmWorkHours;
+-------+------------+-------+
| empId | day | hours |
+-------+------------+-------+
| 17 | 2021-08-15 | 4.00 |
| 17 | 2021-09-18 | 15.00 |
| 25 | 2021-08-17 | 8.00 |
| 38 | 2021-08-20 | 10.00 |
| 64 | 2021-08-31 | 7.50 |
+-------+------------+-------+
5 rows in set (0.001 sec)
MariaDB [test]> select * from Administrator;
+-------+--------------+--------+
| empId | name | gender |
+-------+--------------+--------+
| 17 | Rishabh Pant | M |
| 25 | Mary Kom | F |
| 38 | Sarah Taylor | F |
| 64 | Hasan Ali | M |
+-------+--------------+--------+我的查询必须返回每个管理员的empId、名称和总工时。
这是我想出的最好的查询,我似乎无法得到每个管理员的总数。
select a.empId , a.name , sum(distinct h.hours) from Administrator AS a , AdmWorkHours AS h order by h.hours asc;发布于 2021-10-20 07:54:24
使用左联接:
SELECT a.empId, a.name, COALESCE(SUM(a.hours), 0) AS hours_worked
FROM Administrator a
LEFT JOIN AdmWorkHours awh
ON awh.empId = a.empId
GROUP BY a.empId, a.name;当前查询的主要问题是,您是在没有任何条件的情况下进行连接,因此默认为交叉连接。您还使用了旧的隐式联接语法。考虑在这里使用我上面的版本来获得最好的结果。
发布于 2021-10-20 07:55:01
看起来您忘记了联接条件,只需要一个组:
select empId, name, sum(hours)
from Administrator natural join AdmWorkHours
group group by empId, name;当管理员没有时间时,您可以添加@TimBiegeleisen并离开join的coalesce()。我的解决方案就是不显示那些记录。
https://stackoverflow.com/questions/69642224
复制相似问题