SQL在不同条件下多次选择同一列

时间:2019-06-26 03:59:25

标签: sql

我正在尝试显示几个分支机构及其相应的经理姓名,主管人数以及男女职员人数。但是,当我执行查询时会弹出以下错误消息,“列'STAFF_T.stf_first_name'在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。”请帮助我:)

127.0.0.1:5000

This is my current output 当前显示主管,男性员工和女性员工的总数。它应该显示基于每个分支ID的主管和员工人数。

3 个答案:

答案 0 :(得分:0)

下面的查询应该起作用,

SELECT 
    b.brc_id AS [Branch ID]
    ,s.stf_first_name AS [Manager First Name]
    ,s.stf_last_name AS [Manager Last Name]
    ,COUNT(CASE WHEN s.stf_position = 'Supervisor' THEN 1 ELSE 0 END) AS [Number of Supervisor]
    ,COUNT(CASE WHEN s.stf_position = 'Staff' AND s.stf_gender = 'Male' THEN 1 ELSE 0 END) AS [Male Staff]
    ,COUNT(CASE WHEN s.stf_position = 'Staff' AND s.stf_gender = 'Female' THEN 1 ELSE 0 END) AS [Female Staff]
FROM BRANCH_T b
INNER JOIN STAFF_T s 
    ON 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

答案 1 :(得分:0)

您正在混合汇总查询和非汇总查询,如错误消息所述。我会查询分支表并将其连接两次-一次在人员表上获取经理的详细信息,一次在人员表上进行汇总查询以获取计数:

SELECT b.brc_id AS 'Branch ID',
       m.stf_first_name AS 'Manager First Name',
       m.stf_last_name AS 'Manager Last Name',
       c.supervisor_count,
       c.male_staff,
       c.female_staff
FROM   branch_t b
JOIN   staff_t m ON b.brc_manager = m.stf_id
JOIN   (SELECT     stf_brc_id, 
                   COUNT(CASE sa.stf_position WHEN 'Supervisor' THEN 1 END)
                         AS supervisor_count,
                   COUNT(CASE WHEN sb.stf_position = 'Staff' AND
                                   sb.stf_gender = 'Male' THEN 1 END) AS male_staff, 
                   COUNT(CASE WHEN sb.stf_position = 'Staff' AND
                                   sb.stf_gender = 'Female' THEN 1 END) AS female_staff
        FROM     staff
        GROUP BY stf_brc_id) c ON c.stf_brc_id = b.brc_id

答案 2 :(得分:0)

使用RIGHT JOIN可以使您的查询简单如下-

SELECT  S.stf_brc_id,
MAX(CASE WHEN B.brc_id IS NULL THEN NULL ELSE S.stf_first_name END) F_name,
MAX(CASE WHEN B.brc_id IS NULL THEN NULL ELSE S.stf_last_name END) L_name,
SUM(CASE WHEN S.stf_position = 'Supervisor' THEN 1 ELSE 0 END ) 'Number of Supervisor',
SUM(CASE WHEN S.stf_position = 'Staff' AND S.stf_gender = 'Male' THEN 1 ELSE 0 END ) 'Male Staff',
SUM(CASE WHEN S.stf_position = 'Staff' AND S.stf_gender = 'Female' THEN 1 ELSE 0 END ) 'Female Staff'
FROM BRANCH_T B 
RIGHT JOIN STAFF_T S ON  B.brc_id = S.stf_brc_id AND B.brc_manager = S.stf_id
GROUP BY  S.stf_brc_id