解决!谢谢你的帮助!
如何修复此查询
所以Pet的表格字段是
Pet_Code,名称,Employee_code,类型,性别
Employees表的字段是
Employee_code,姓氏,将First_Name,部
这是我尝试但不起作用的地方:
SELECT First_Name,Last_Name
FROM employees E,pets P
WHERE P.Employee_code=E.Employee_code AND COUNT(Type='C') > Count(Type='D');
答案 0 :(得分:0)
我想你可以试试这个:
SELECT
Employee_code,
Last_Name,
First_Name,
SUM(CASE WHEN Type = 'C' THEN 1 ELSE 0 END) AS CAT,
SUM(CASE WHEN Type = 'D' THEN 1 ELSE 0 END) AS DOG
FROM Employees_TABLE E
JOIN PET_TABLE P ON E.Employee_code = P.Employee_code
GROUP BY Employee_code
HAVING SUM(CASE WHEN Type = 'C' THEN 1 ELSE 0 END) > SUM(CASE WHEN Type = 'D' THEN 1 ELSE 0 END)
答案 1 :(得分:0)
好的,你可以试试这个:
SELECT DISTINCT
E.Employee_code, E.Last_Name, E.Department,
(SELECT COUNT(*) FROM pet WHERE Employee_code = E.Employee_code AND Type = 'C') AS cats,
(SELECT COUNT(*) FROM pet WHERE Employee_code = E.Employee_code AND Type = 'D') AS dogs
FROM employee E
LEFT JOIN pet P ON E.Employee_code = P.Employee_code
GROUP BY E.Employee_code
HAVING cats > dogs
它就像前一个,但更简单的是
答案 2 :(得分:0)
也许你可以试试这个:
SELECT e.First_Name, e.Last_Name
FROM employees e INNER JOIN pets p ON e.Employee_code = p.Employee_code
WHERE
(SELECT COUNT(*)
FROM pets p1
WHERE p1.Type = 'C' AND p.Employee_code = p1.Employee_code) >
(SELECT COUNT(*)
FROM pets p1
WHERE p1.Type = 'D' AND p.Employee_code = p1.Employee_code)
GROUP BY e.Employee_code;
这可能不是最佳解决方案,但应该完成这项工作。
答案 3 :(得分:0)
select min(e.First_Name), min(e.Last_Name)
from emp e left outer join pets p
on p.Employee_Code = e.Employee_Code
group by e.Employee_Code
having
count(case when Type = 'C' then 1 end) >
count(case when Type = 'D' then 1 end)