在HAVING和WHERE子句之间使用OR运算符进行SQL查询

时间:2018-01-02 10:26:55

标签: mysql sql database

是否可以在单个SQL查询中将OR运算符中的having和where子句组合在一起?

也许不是最好的例子,但你会明白这个想法:

从员工表中选择HR(使用where子句)或者为所有员工支付超过25000的部门(使用having子句)。 那么我们如何在下面的查询中获得OR条件?或者将查询分成2个查询会更好。

SELECT dept, SUM (salary) 
FROM employee 
WHERE dept = "HR"
GROUP BY dept 
HAVING SUM (salary) > 25000

3 个答案:

答案 0 :(得分:4)

以下内容可行 - 您无需在HAVING子句中指定聚合

SELECT dept, SUM (salary) 
FROM employee 
GROUP BY dept 
HAVING dept = "HR" or SUM (salary) > 25000

但您的声明"支付所有员工超过25000"不清楚。你想要吗

所有员工每人收入超过25000的部门,或 所有员工总共收入超过25000的部门?

上面的查询为您提供了第二个选项,因为它最接近您的原始查询

答案 1 :(得分:2)

GROUP BY部分包装在派生表中。然后将条件应用于其结果:

select dept, salarysum
from
(
    SELECT dept, SUM (salary) as salarysum
    FROM employee 
    GROUP BY dept
) dt
where salarysum > 25000 or dept = "HR"

或者,也许"向所有员工支付超过25000" ,意味着没有部门员工的收入低于25000?

select dept, minsalary
from
(
    SELECT dept, MIN(salary) as minsalary
    FROM employee 
    GROUP BY dept
) dt
where minsalary > 25000 or dept = "HR"

答案 2 :(得分:1)

也许你想要所有工资超过25000的部门。

drop table if exists employees;
create table employees(id int auto_increment primary key, dept varchar(2), salary int);

insert into employees (dept,salary)
values
('HR',10000),('aa',10000),('aa',45000),('bb',25000),('cc',26000),('cc',26000);

select dept,sum(salary) sumsalary,count(*) obs, sum(case when salary > 25000 then 1 else 0 end) over25000
from employees
group by dept having obs = over25000 or dept = 'hr'

+------+-----------+-----+-----------+
| dept | sumsalary | obs | over25000 |
+------+-----------+-----+-----------+
| cc   |     52000 |   2 |         2 |
| HR   |     10000 |   1 |         0 |
+------+-----------+-----+-----------+
2 rows in set (0.01 sec)