我有两个这样的表,现在查询是显示empid&列表每月工作时间最短的员工姓名id
o / p应该是这样的。moth_ending Emp_id name
20150131 1001 baba
20150228 1001 baba
20150331 1001 baba
我尝试了这段代码。
select Month_ending,Name,Total_workinghours
from Employee_details left join
Dim_employee
on Employee_details.Emp_id = Dim_employee.Emp_id
答案 0 :(得分:1)
学习使用表别名。我想这就是你想要的:
select ed.Month_ending, ed.Emp_id, e.name
from Employee_details ed left join
Dim_employee e
on ed.Emp_id = e.Emp_id;
我不明白为什么left join
是必要的。如果您的数据库设置正确,那么employee_details
应该引用有效的员工。
答案 1 :(得分:1)
希望这会达到您的要求。检查此代码,并在发生错误时进行必要的更改。
;with cte as(
SELECT ROW_NUMBER()over( partition by ed.MONTH_ENDING order by ed.TOTAL_WORKINGHOURS asc)as Rnum,ed.MONTH_ENDING,de.NAME,ed.TOTAL_WORKINGHOURS
FROM EMPLOYEE_DETAILS ed
INNER JOIN DIM_EMPLOYEE de
ON ed.EMP_ID = de.DIM_EMPLOYEE.EMP_ID
)
select MONTH_ENDING,NAME,TOTAL_WORKINGHOURS from CTE where Rnum=1
注意:根据要求传递Rnum值,即1,2,3..etc
答案 2 :(得分:0)
您需要先找出按月计算的最短工作时间,将其放入子查询中,然后查找主表。
您可以尝试以下方法:
SELECT ed.MONTH_ENDING,de.NAME,ed.TOTAL_WORKINGHOURS
FROM EMPLOYEE_DETAILS ed
INNER JOIN DIM_EMPLOYEE de
ON ed.EMP_ID = de.DIM_EMPLOYEE.EMP_ID
WHERE (ed.MONTH_ENDING,ed.TOTAL_WORKINGHOURS)
IN (
SELECT ed_i.MONTH_ENDING,MIN(ed_i.TOTAL_WORKINGHOURS)
FROM EMPLOYEE_DETAILS ed_i
GROUP BY ed_i.MONTH_ENDING
);
答案 3 :(得分:0)
以cte为( SELECT ROW_NUMBER()over(由ed.TOTAL_WORKINGHOURS asc编写的ed.MONTH_ENDING分区)作为Rnum,ed.MONTH_ENDING,de.NAME,ed.TOTAL_WORKINGHOURS 来自EMPLOYEE_DETAILS编辑 INNER JOIN DIM_EMPLOYEE de ON ed.EMP_ID = de.EMP_ID ) 从CTE中选择MONTH_ENDING,NAME,TOTAL_WORKINGHOURS,其中Rnum = 1