【问题标题】:Return all locations, users, and roles where a user has 'X' role in each location (SQL Server)返回用户在每个位置具有“X”角色的所有位置、用户和角色(SQL Server)
【发布时间】:2014-11-15 18:40:31
【问题描述】:

我需要编写一个查询,以从用户在每个位置具有“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 中包含角色 ID 2 的所有位置 (A)、用户 (B) 和角色 (C)。

上表的预期结果是:

A                B            C
location 1       1            1
location 1       1            2
location 1       2            1
location 1       2            2

提前致谢!

【问题讨论】:

  • 我不明白您所说的“位置和用户包含角色 ID 2 的位置”是什么意思 - 您的预期结果似乎只是位置 1 数据?
  • select * from table1 where A = 'location 1'是你想要的吗?

标签: sql sql-server


【解决方案1】:
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】:

    你想要的叫做“关系划分”。唯一的问题是您的文字描述与您想要的输出相矛盾。对于提供的输出,措辞应该是“获取所有用户都是角色 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 之类的术语来操作 - 它让我心烦意乱。所以上面是一张合适的表格。)

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2016-04-30
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      相关资源
      最近更新 更多