0
我需要找到員工Milo
的最高工作經驗。這裏是我的表:如何在多個連接中使用聚合函數?
CREATE TABLE company (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(250) NOT NULL
);
CREATE TABLE employee (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(250) NOT NULL
);
CREATE TABLE company_employee (
company_id INT NOT NULL,
employee_id INT NOT NULL,
hire_date DATE DEFAULT NULL,
resign_date DATE DEFAULT NULL,
FOREIGN KEY (company_id) REFERENCES company (id),
FOREIGN KEY (employee_id) REFERENCES employee (id)
);
而且我查詢它獲取米洛
的所有公司SELECT
employee.name, company.name, company_employee.hire_date,
company_employee.resign_date,
(company_employee.resign_date - company_employee.hire_date)
FROM company
JOIN company_employee
ON (company.id = company_employee.company_id)
JOIN employee
ON (company_employee.employee_id = employee.id)
WHERE employee.name = 'Milo'
它返回
+------+--------------+-----------+-------------+-----------------+
| name | company_name | hire_date | resign_date | experience_days |
+------+--------------+-----------+-------------+-----------------+
| Milo | IBM |1997-04-17 | 1998-03-08 | 325 |
| Milo | IBM |2012-04-03 | 2014-02-15 | 683 |
| Milo | IBM |2000-08-10 | 2003-01-01 | 874 |
+------+--------------+-----------+-------------+-----------------+
但我只需要一個記錄,最大的經驗
+------+-----+------------+------------+-----+
| Milo | IBM | 2000-08-10 | 2003-01-01 | 874 |
+------+-----+------------+------------+-----+
UPD:
此查詢查找每個公司
SELECT
company.name,
COUNT(company_employee.employee_id)
FROM company
LEFT JOIN company_employee
ON company.id = company_employee.company_id
GROUP BY company.name
HAVING COUNT(company_employee.employee_id) > 0;
我可以簡化它的所有員工的數量?
如何在我的表中使用SUM函數。任何例子? – Finkelson
SUM()'也是一個聚合函數,你想總結什麼? –
如果我需要輸出所有公司並找到所有公司的員工數量,我應該寫什麼查詢? – Finkelson