我想选择在过去3个月内签署了大部分合同的员工: 表之间的连接是:contracts.responsible references employees(id)
select b.name, b.id, count(*) nr_contracts_last_3_mths
from contracts a join employees b
on a.responsible = b.id and
data between add_months(trunc(sysdate, 'MM'), -1) and trunc(sysdate)
group by b.name, b.id
having count(*) =
(select max(count(responsible))
from contracts, employees
where contracts.responsible = employees.id
group by employees.name
);
结果仅包含空的选定列(无数据)。
预期结果应该响应的名称,他的ID 和值 5 ,因为bellow查询返回5;
select max(count(*)) nr_contracts_last_3_mths from contracts where data
between add_months(trunc(sysdate, 'MM'), -3) and trunc(sysdate)
group by data;
答案 0 :(得分:0)
您的查询不起作用,因为having
子句中的子查询在时间范围内没有条件,因此它返回的计数高于“top”查询中的任何行(如,据推测,员工在过去三个月之前也签订了合同。)
无论如何,更简单的方法是将窗口rank
功能与“顶级”查询结合使用:
SELECT name, id, nr_contracts_last_3_mths
FROM (SELECT b.name AS name,
b.id AS id,
COUNT(*) AS nr_contracts_last_3_mths
RANK() OVER (ORDER BY COUNT(*) DESC) AS rk
FROM contracts a
JOIN employees b ON a.responsible = b.id AND
data BETWEEN
add_months(trunc(sysdate, 'MM'), -1) AND
TRUNC(sysdate)
GROUP BY b.name, b.id)
WHERE rk = 1
答案 1 :(得分:0)
select b.name, b.id, count(*) nr_contracts_last_3_mths
from contracts a join employees b
on a.responsible = b.id and
data between add_months(trunc(sysdate, 'MM'), -3) and trunc(sysdate)
group by b.name, b.id
having count(*) =
(select max(count(*))
from contracts a join employees b
on a.responsible = b.id and
data between add_months(trunc(sysdate, 'MM'), -3) and trunc(sysdate)
group by b.name, b.id
);