0

我正在使用SQL Server 2008 R2從多對多關係表中取回最新記錄

我有three tables在我的數據庫中有many-to-many關係如下。

TblServiceLevel  
Id ServiceLevel Code 
1 C    1 
2 R    1 
3 V    1 
4 R Test   4 
5 C Test   4 
6 S    2 
7 K    3 


TblUser 
Id Name 
1 A 
2 B 
3 C 
4 D 
5 E 
6 F 


TblUserServiceLevel   
Id UserId ServiceLevelId Status 
1 1  1    Active 
2 1  1    Deactive 
3 2  3    Active 
4 3  4    Active 
5 1  5    Active 
6 5  1    Active 
7 2  3    Deactive 
8 3  4    Deactive 
9 5  1    Deactive 
10 2  3    Active 
11 3  4    Active 
12 4  1    Active 

現在,

從這個表,我想是不同用戶存在於TblUserServiceLevel和 有latest service level ="Active"ServiceLevel.Code <> 4.

誰能幫助我?

結果是24用戶ID。

回答

1
select t1.UserId 
from TblUserServiceLevel t1 
inner join (
    select UserId, max (Id) as maxId 
    from TblUserServiceLevel 
    group by UserId 
) t2 on t1.UserId = t2.UserId and t1.Id = t2.maxId 
inner join TblServiceLevel sl on t1.ServiceLevelId = sl.Id and sl.Code <> 4 
where t1.Status = 'Active' 
+0

謝謝GriGrim !!很好的解決方案.. SQL專家現在在Stackoverflow .. Yippi .. :) – Dev

相關問題