我需要编写一个查询来识别用户在每个位置具有“X”角色的表中的所有位置,用户和角色。
该表有三列(A =位置,b =用户,c =角色)。
A是varchar,b是INT,c是INT。假设该表包含以下内容:
A B C
location 1 1 1
location 1 1 2
location 2 1 1
location 1 2 1
location 1 2 2
location 3 2 1
我想要返回位置(A),用户(B)和角色(C),其中位置(A)和用户(B)在C中包含roleID 2。
上表的预期结果是:
A B C
location 1 1 1
location 1 1 2
location 1 2 1
location 1 2 2
提前致谢!
SELECT *
FROM YourTable t1
WHERE EXISTS (
SELECT 1
FROM YourTable t2
WHERE t1.A = t2.A
and t1.B = t2.B
and t2.C = 2
)
你想要什么叫做“关系师”。唯一的问题是你的文字描述与你想要的输出相矛盾。对于提供的输出,措辞应该是“获取所有用户都是角色2成员的位置的所有数据”,这是完全不同的。无论如何:
declare @t table (
LocationId varchar(20) not null,
UserId int not null,
RoleId int not null
);
insert into @t values
('location 1',1, 1),
('location 1',1, 2),
('location 2',1, 1),
('location 1',2, 1),
('location 1',2, 2),
('location 3',2, 1);
-- What you have said
select t.*
from @t t
inner join (
select c.LocationId, c.UserId
from @t c
where c.RoleId = 2
group by c.LocationId, c.UserId
having count(*) = (select count(distinct cn.LocationId) from @t cn)
) sq on sq.UserId = t.UserId and sq.LocationId = t.LocationId;
-- What you seem to need
select *
from @t r
where exists (
select t.LocationId
from @t t
where t.LocationId = r.LocationId
group by t.LocationId
having count(distinct t.UserId) = count(distinct case t.RoleId when 2 then t.UserId end)
);
(我不能像A,B,C那样操作 - 它让我的思绪蹒跚。所以上面是一张合适的表格。)