我正在使用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.
和2
任何人都可以帮助我吗?
结果是4
和{{1}}用户ID。
答案 0 :(得分: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'