我正在尝试为视图编写查询,但我没有抓住它。 我有两张桌子
user_roles
id user_id role_id
1 1 4
2 1 1
3 1 2
4 1 3
user_roles_hst
id UserRolesID RoleEnabled creator
1 1 1 1
2 1 0 1
3 1 1 1
4 2 0 1
5 2 1 1
6 3 0 1
7 4 0 1
现在我想要一个包含所有用户角色及其最新启用状态的视图 像这样
vw_user_roles
user_id role_id RoleEnabled
1 4 1
1 1 1
1 2 0
1 3 0
user_roles_hst存储角色状态更改的历史记录,因为它们已启用或禁用但在vw_user_roles中,我需要每个或role_id的最新状态
查询:
select * from
(select x.user_id, x.UserRolesID, x.RoleEnabled from
(select h.id, u.user_id, h.UserRolesID, h.RoleEnabled from UserRoles u, UserRoles_HST h
where u.id = h.UserRolesID
group by h.id, h.UserRolesID, h.RoleEnabled, u.user_id
) x
order by x.id desc
) y
group by y.user_id, y.UserRolesID, y.RoleEnabled
我尝试了上述查询,但后来我意识到我无法在子查询中使用order by
我需要有关如何获得正确查询的帮助。
答案 0 :(得分:1)
Declare @user_roles table (id int, user_id int, role_id int)
Declare @user_roles_hst table (id int, userrolesid int, roleenabled int, creator int)
insert into @user_roles values
(1,1,4),
(2,1,1),
(3,1,2),
(4,1,3)
insert into @user_roles_hst values
(1, 1, 1, 1),
(2, 1, 0, 1),
(3, 1, 1, 1),
(4, 2, 0, 1),
(5, 2, 1, 1),
(6, 3, 0, 1),
(7, 4, 0, 1)
select ur.user_id,ur.role_id,x.roleenabled
from @user_roles ur
join (
Select row_number() over (partition by userrolesid order by id desc) rn,*
from @user_roles_hst) x on ur.id = x.userrolesid
where rn = 1
答案 1 :(得分:1)
declare @user_roles table ( id int, user_id int, role_id int);
insert into @user_roles values
(1, 1, 4),
(2, 1, 1),
(3, 1, 2),
(4, 1, 3)
declare @user_roles_hst table (id int, UserRolesID int, RoleEnabled int, creator int);
insert into @user_roles_hst values
(1, 1, 1, 1),
(2, 1, 0, 1),
(3, 1, 1, 1),
(4, 2, 0, 1),
(5, 2, 1, 1),
(6, 3, 0, 1),
(7, 4, 0, 1)
select r.user_id,
r.role_id,
a.RoleEnabled
from @user_roles r outer apply (select top 1 *
from @user_roles_hst h
where h.UserRolesID = r.id
order by id desc) a;
答案 2 :(得分:0)
每个user_id的vw_user_roles
的最大ID:
SELECT max(id) as maxID FROM user_roles_hst GROUP BY userRolesID;
使用它来获取每个maxID
的表格中的记录:
SELECT t2.user_id, t1.UserRolesID, t1.rolesEnabled
FROM user_roles_hst t1
INNER JOIN user_roles t2 ON
t1.userRolesID = t2.role_id
WHERE id IN (SELECT max(id) as maxID FROM user_roles_hst GROUP BY userRolesID);
答案 3 :(得分:0)
我假设:
creator
真的是用户。userRoleId
是用户角色然后您可以使用row_number()
:
select urh.creator as user_id, userRoleId, as role_id, role_enabled as enabled
from (select urh.*,
row_number() over (partition by creator, userRoleId order by id desc) as seqnum
from user_roles_hst urh
) urh
where seqnum = 1;