0

SQL Server 2008 R2을 사용 중입니다.다 대다 관계 테이블에서 최신 레코드 가져 오기

내 데이터베이스에 three tablesmany-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