我正在尝试计算某些商店中有多少员工,并按照包含1-Emplyee.EMP_CODE,STORE_CODE表和2-STORE.store_code的2个表的商店代码进行分组... (STORE tbl - 不包含EMP_CODE)所以我甚至可能没有走上正轨。
SELECT c.EMP_CODE,c.STORE_CODE,s.STORE_CODE,COUNT(c.EMP_CODE)
FROM EMPLOYEE c
LEFT OUTER JOIN STORE s
on c.STORE_CODE=s.STORE_CODE
GROUP BY s.STORE_CODE
;
继续收到错误:
Msg 8120,Level 16,State 1,Line 1 Column' EMPLOYEE.EMP_CODE'是 在选择列表中无效,因为它不包含在任何一个中 聚合函数或GROUP BY子句。
答案 0 :(得分:0)
如错误所述,您需要在GROUP BY
中添加所有非汇总列,而不是您选择的列。
选项1 :将所有非汇总列添加到GROUP BY
SELECT c.EMP_CODE,c.STORE_CODE,s.STORE_CODE,COUNT(c.EMP_CODE)
FROM EMPLOYEE c
LEFT OUTER JOIN STORE s
on c.STORE_CODE=s.STORE_CODE
GROUP BY c.EMP_CODE,c.STORE_CODE,s.STORE_CODE;
选项2 :从原始SELECT
SELECT s.STORE_CODE, COUNT(c.EMP_CODE)
FROM EMPLOYEE c
LEFT OUTER JOIN STORE s
on c.STORE_CODE=s.STORE_CODE
GROUP BY s.STORE_CODE;
选项3 :使用嵌套选择COUNT(c.EMP_CODE)
且只使用GROUP BY s.STORE_CODE
,同时仍然可以选择所需的所有列。类似的东西:
SELECT c.EMP_CODE,c.STORE_CODE,s.STORE_CODE,A.Count_Emp
FROM EMPLOYEE c
LEFT OUTER JOIN STORE s
on c.STORE_CODE=s.STORE_CODE
LEFT OUTER JOIN (
SELECT s.STORE_CODE, COUNT(c.EMP_CODE) as 'Count_Emp'
FROM EMPLOYEE c
LEFT OUTER JOIN STORE s
ON c.STORE_CODE=s.STORE_CODE
GROUP BY s.STORE_CODE
) A on A.STORE_CODE = c.STORE_CODE;
答案 1 :(得分:0)
您缺少GROUP BY子句中的所有列。那应该解决它!