Mysql 如何使用一个不同的条件连接两个相同的查询而不使用union

Mysql 如何使用一个不同的条件连接两个相同的查询而不使用union,mysql,Mysql,职位总数=(经理+员工)/经理 我有两个几乎相同但条件不同的查询employee.status。我希望以经理和员工的身份获取结果,并需要在一个查询中计算所有工作的总数使用条件聚合: select date_format(FROM_UNIXTIME(employee.inserted_time), "%X-%V") as Week, count(employee.id) as managers from jobs join dept on jobs.id = dept.id join employ

职位总数=(经理+员工)/经理


我有两个几乎相同但条件不同的查询employee.status。我希望以经理和员工的身份获取结果,并需要在一个查询中计算所有工作的总数

使用条件聚合:

select date_format(FROM_UNIXTIME(employee.inserted_time), "%X-%V") as Week, count(employee.id) as managers
from jobs
join dept on jobs.id = dept.id
join employee on jobs.id = employee.id and employee.salary > 10000
where employee.status ='rejected' or 'cancelled' 
group by Week;

select date_format(FROM_UNIXTIME(employee.inserted_time), "%X-%V") as Week, count(employee.id) as employees
from jobs
join dept on jobs.id = dept.id
join employee on jobs.id = employee.id and employee.salary > 10000
where employee.status ='accepted' or 'working' 
group by Week;

您可以在
SUM()中使用
CASE
在单个查询中执行此操作。例如:

SELECT
    DATE_FORMAT(FROM_UNIXTIME(e.inserted_time), '%X-%V') AS Week,
    COUNT(CASE WHEN d.status in ('rejected', 'cancelled') THEN e.id END) AS managers,
    COUNT(CASE WHEN d.status in ('accepted', 'working') THEN e.id END) AS employees
FROM jobs j
INNER JOIN dept d ON j.id = d.id
INNER JOIN employee e ON j.id = e.id AND e.salary > 10000
GROUP BY Week;

向我们展示具有预期输出的示例数据。
select
  date_format(FROM_UNIXTIME(employee.inserted_time), "%X-%V") as Week,
  sum(case when employee.status in ('rejected', 'cancelled') then 1 else 0 end) 
    as managers
  sum(case when employee.status in ('accepted', 'working') then 1 else 0 end)
    as employees
from jobs
join dept on jobs.id = dept.id
join employee on jobs.id = employee.id and employee.salary > 10000
where employee.status in ('rejected', 'cancelled', 'accepted', 'working')
group by Week