我有一个关于访问中的SQL查询的问题(我刚开始就像3天前一样)
所以有2个表:雇员和部门,我想要的是创建一个查询,显示每个雇员的姓名和身份以及他管理的部门数量。
Employee( ID, NAME, social_security_of_employe)
Department(department_id, social_security_of_employee)
(社会保障是我的主要关键) 我的尝试是:
SELECT E.ID, E.NAME, COUNT(D.SOCIAL_SECURITY) AS NUMBER_OF_DEPARTMENTS
FROM EMPLOYEE E
INNER JOIN DEPARTMENT D
WHERE D.SOCIAL_SECURITY=E.SOCIAL_SECURITY
GROUP BY SOCIAL_SECURITY
提前致谢
答案 0 :(得分:1)
MS Access的正确语法是:
SELECT E.ID, E.NAME, COUNT(D.SOCIAL_SECURITY) AS NUMBER_OF_DEPARTMENTS
FROM EMPLOYEE as E INNER JOIN
DEPARTMENT as D
ON D.SOCIAL_SECURITY = E.SOCIAL_SECURITY
GROUP BY E.ID, E.NAME;
的变化:
as
表别名。WHERE
子句应为ON
子句。GROUP BY
中的列需要与SELECT
中的未聚合列相匹配。答案 1 :(得分:0)
您需要按选择列表中列出的所有非聚合列进行分组,即:
SELECT E.ID, E.NAME, COUNT(D.SOCIAL_SECURITY) AS NUMBER_OF_DEPARTMENTS
FROM EMPLOYEE E
INNER JOIN DEPARTMENT D
ON D.SOCIAL_SECURITY=E.SOCIAL_SECURITY
GROUP BY E.ID, E.NAME;
而不是SOCIAL_SECURITY
(您正在使用COUNT
聚合)
由于E.ID
和E.NAME
直接相关,因此只有一个级别的分组。