你好我试图计算每个员工的工资行数。
我有前两张桌子。
表员工
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 :(得分: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
这是一个小提琴
答案 1 :(得分: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