我插入了一个查询,以显示公司每个分支机构中主管,男女员工的总数。但是,我的查询中有一个错误,我不知道该如何解决...请帮助我,谢谢。
bar=dog
输出应显示公司每个分支机构的主管,男女员工总数。但是会弹出以下错误消息,
Msg 512,第16级,状态1,第57行
子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做
答案 0 :(得分:0)
这是因为您的子查询是在原始表上执行的,原始表具有多个元组bc.brc_id,sc.stf_first_name,sc.stf_last_name。如果您要依靠分组数据,请像这样使用SUM CASE WHEN或SUM IIF:
SELECT b.brc_id AS 'Branch ID',
s.stf_first_name AS 'Manager First Name',
s.stf_last_name AS 'Manager Last Name',
SUM(IIF(s.stf_position = 'Supervisor', 1, 0)) AS
'Number of Supervisor',
SUM(IIF((s.stf_position = 'Staff') AND (s.stf_gender = 'Male'), 1, 0)) AS 'Male
Staff',
SUM(IIF((s.stf_position = 'Staff') AND (s.stf_gender = 'Female'), 1, 0)) AS 'Female Staff'
FROM
BRANCH_T b, STAFF_T s
WHERE
(b.brc_id = s.stf_brc_id) AND (b.brc_manager = s.stf_id)
GROUP BY
b.brc_id, s.stf_first_name, s.stf_last_name
第二件事,where子句的条件:
AND (b.brc_manager = s.stf_id)
似乎是错误的。在这种情况下,您只能获得每个分支的经理。如果要获取管理员名称,则必须再加入STAFF_T。最终查询应为:
SELECT b.brc_id AS 'Branch ID',
m.stf_first_name AS 'Manager First Name',
m.stf_last_name AS 'Manager Last Name',
SUM(IIF(s.stf_position = 'Supervisor', 1, 0)) AS
'Number of Supervisor',
SUM(IIF((s.stf_position = 'Staff') AND (s.stf_gender = 'Male'), 1, 0)) AS 'Male
Staff',
SUM(IIF((s.stf_position = 'Staff') AND (s.stf_gender = 'Female'), 1, 0)) AS 'Female Staff'
FROM
BRANCH_T b
INNER JOIN STAFF_T s ON b.brc_id = s.stf_brc_id
LEFT JOIN STAFF_T m ON b.brc_manager = m.stf_id
GROUP BY
b.brc_id, m.stf_first_name, m.stf_last_name