2016-01-15 34 views
0

你好我试图计算每个员工的薪水行数。如何计算行并仍然显示所有行? mysql

我有两个表为ex。

表雇员

id_____________name 

1..............sam 

2..............greg 

3..............vic 

4..............steve 

表薪水

id____________salary 

1.............10000 

1.............15000 

2.............30000 

3.............13000 

4.............90000 

4.............20000 

结果我需要的是

id| name | salary| count 

1 | sam | 10000 | 2 

1 | sam | 15000 | 2 

2 | greg | 30000 | 1 

3 | vic | 13000 | 1 

4 |steve | 90000 | 2 

4 |steve | 90000 | 2 

到总结:我有4名雇员过去的工资。我试图创建一个查询,显示薪金列表和员工有多少薪水。

这是我曾尝试,但我得到6个性化......

create temporary table rates 
SELECT e.id, e.name, s.salary, count(*) as count 
FROM employee e 
INNER JOIN salary s ON e.id = s.id 
GROUP BY name, s.salary 
ORDER BY name; 

create temporary table sum 
select r.id, sum(count) as sum 
from rates r; 

select * from rates 
LEFT OUTER JOIN sum s ON r.id = s.id; 

我试着自我加入,但没有奏效。

提前致谢!

回答

0

您将要执行的内部连接的薪水和员工表

您还希望包括嵌套SELECT声明之间。

SELECT e.id, e.name, s.salary, 
(SELECT COUNT(*) FROM salary s 
     WHERE employee_id = id) as COUNT 
FROM employees e 
INNER JOIN salary s ON employees.id = salary.id 

这里是一个小提琴

http://sqlfiddle.com/#!9/b94ec/9/0

0

这里是SQL Server代码,可以给你想要的结果。

select 
     s.empid, e.name, s.salary, 
     cnt.SalaryCount 
    from 
     salary s 
     inner join emp e on s.empid = e.id 
     outer apply 
     (select count(*) as SalaryCount from salary where empid = e.id) cnt