在having和where子句之间使用or运算符的sql查询

h5qlskok  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(339)

在一个sql查询中,是否可以在or运算符中组合having和where子句?
也许不是最好的例子,但你会想到:
从employee表中选择为hr(使用where子句)或向所有员工支付超过25000(使用having子句)的部门。那么我们如何在下面的查询中得到or条件呢?或者最好将查询分为两个查询。

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

lh80um4z1#

下面的方法将起作用-您不必在having子句中指定聚合

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

但你的说法“给所有员工的工资超过25000”并不清楚。你想要什么
员工人均收入超过25000的部门,或者员工总收入超过25000的部门?
上面的查询提供了第二个选项,因为它最接近原始查询

vd2z7a6w

vd2z7a6w2#

也许你想要一个薪水超过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)
gcuhipw9

gcuhipw93#

Package 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"

相关问题