根据Partition by或Self join加入3个表

时间:2015-12-22 10:17:36

标签: sql sql-server-2008

我有以下表格

tbl1 (empID, Name, ctNo)

tbl2 (salID, empID, salry)

tbl3 (histryID, salDate, empID, salID)

期望输出(empID,Name,salary,Salary_Date)

对于工资日期,我只希望显示最后一个salary_date。

(可能通过使用Partitiion或Selfjoin方法。)

谢谢。

3 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

select t1.empID, t1.Name, t2.salry as salary, top (t3.salDate) as Salary_Date from tbl1 t1, tbl2 t2, tbl3 t3 on t1.empID=t2.empID and t1.empID=t3.empID

注意:指向正确的方向。未经测试。

答案 1 :(得分:0)

您可以使用row_number窗口函数执行此操作:

select t1.empid, t1.name, t3.saldate, t2.salary
from tbl1 t1
join(select *, row_number() over(partition by empid order by saldate desc) rn 
     from tbl3)t3 on t1.empid = t3.empid and t3.rn = 1
join tbl2 t2 on t3.empid = t2.empid AND t3.salid = t2.salid

答案 2 :(得分:0)

以下查询可以回答您的问题

Create table #tbl1 (empID int , Name varchar(11), ctNo int)
Create table #tbl2 (salID int, empID int, salry int)
Create table  #tbl3 (histryID int, salDate DATE, empID int, salID int) 


INSERT INTO #tbl1
values(1,'Dinesh',23),(2,'Raj',11)
INSERT INTO #tbl2
values(1,1,1000),(2,1,2000),(3,2,100),(4,2,500)
INSERT INTO #tbl3
values(1,'20020101',1,1),(2,'20020201',1,2),(3,'20020101',2,3),(4,'20020201',2,4)
SELECT M1.* FROM(
SELECT T1.empID,T1.Name,T2.salry,T3.salDate FROM
#tbl1 AS T1
INNER join #tbl2 AS T2
ON T1.empID=T2.empID
INNER join #tbl3 AS T3
ON T1.empID=T3.empID AND T2.salID =T3.salID
) AS M1
INNER JOIN
(
SELECT empID,MAX(salDate) AS SALDATE FROM #tbl3 GROUP BY empID) AS M2
ON M1.SALDATE=M2.salDate AND M1.empID=M2.empID