sql count函数

时间:2012-04-03 17:09:19

标签: mysql sql

您好我有三张桌子,我想知道一名员工的工资是多少就有多少工作

第一个SQL查询为我提供了已收到1000份工作的所有员工的姓名

SELECT distinct first_name 
FROM employee, job, link 
WHERE job.wage = 1000 
  AND job.job_id = link.job_id and employee.employee_id = link.employee_id;

第二个SQL查询为我提供了所有员工的总数,即他们为1000提供的工作量

SELECT count(wage) 
FROM employee, job, link 
WHERE job.wage = 1000 
  AND job.job_id = link.job_id and employee.employee_id = link.employee_id;

我想知道是否有办法加入这两个查询,并为每个特定员工制作第二个查询?

3 个答案:

答案 0 :(得分:1)

下面的内容应该可以正常工作,您不再需要使用不同的first_name。

select first_name, COUNT(wage) FROM employee, job, link  WHERE job.wage = 1000    AND job.job_id = link.job_id and employee.employee_id = link.employee_id
GROUP BY first_name

答案 1 :(得分:1)

您可能需要按关键字分组使用

SELECT count(wage), first_name
FROM employee, job, link 
WHERE job.wage = 1000 
  AND job.job_id = link.job_id and employee.employee_id = link.employee_id;
GROUP BY first_name

这样做的缺点是,如果有不同的员工具有相同的first_name,它会考虑相同的计数。

答案 2 :(得分:1)

我还建议将隐式连接更改为显式连接:

SELECT employee.employee_id, first_name, last_name, count(wage) as wage_count
FROM 
    employee
    JOIN link ON employee.employee_id = link.employee_id
    JOIN job ON job.job_id = link.job_id
WHERE job.wage = 1000 
GROUP BY employee.employee_id, first_name, last_name