按两位列分组

时间:2017-04-18 07:55:02

标签: mysql

我想GROUP BY两位列,其值为true。但我有两个列分隔,如何在位列为真的情况下加入它们?

SELECT     employees.employee_id, employees.last_name, 
           employees.first_name, employees.middle_name, 
           employee_role.isAdmin, employee_role.isEmployee
FROM       employees
INNER JOIN employee_role ON employee_role.employee_id = employees.id
INNER JOIN passwords ON passwords.id = employees.password_id
WHERE      employees.employee_id = pIN_employeeId AND passwords.password = pIN_password;

草案输出:

employee_id | last_name | first_name | middle_name | isAdmin | isEmployee
------------+-----------+------------+-------------+---------+------------
  20140540  | Armstrong | Billie Joe |     A       |   0     |    1
  20140540  | Armstrong | Billie Joe |     A       |   1     |    0

预期产出:

employee_id | last_name | first_name | middle_name | isAdmin | isEmployee
------------+-----------+------------+-------------+---------+------------
  20140540  | Armstrong | Billie Joe |     A       |   1     |    1

1 个答案:

答案 0 :(得分:2)

您可以将MaxGROUP BY

一起使用
SELECT     employees.employee_id, employees.last_name, 
           employees.first_name, employees.middle_name, 
           Max(employee_role.isAdmin), 
           Max(employee_role.isEmployee)
FROM       employees
INNER JOIN employee_role ON employee_role.employee_id = employees.id
INNER JOIN passwords     ON passwords.id = employees.password_id
WHERE      employees.employee_id = pIN_employeeId AND passwords.password = pIN_password
GROUP BY   employees.employee_id;

如果 employee_id 不是主键,则还需要在GROUP BY子句中添加其他列:

GROUP BY   employees.employee_id, employees.last_name, 
           employees.first_name, employees.middle_name;

在其他数据库中,甚至需要添加这些列。

如果您只想包含具有 isAdmin 位设置记录的员工,并且还设置了 isEmployee 设置的记录,排除所有其他情况,则像这样添加HAVING子句:

SELECT     employees.employee_id, employees.last_name, 
           employees.first_name, employees.middle_name, 
           Max(employee_role.isAdmin), 
           Max(employee_role.isEmployee)
FROM       employees
INNER JOIN employee_role ON employee_role.employee_id = employees.id
INNER JOIN passwords     ON passwords.id = employees.password_id
WHERE      employees.employee_id = pIN_employeeId AND passwords.password = pIN_password
GROUP BY   employees.employee_id
HAVING     Max(employee_role.isAdmin) = 1 
AND        Max(employee_role.isEmployee) = 1;