SQL查询:查看用户和组数组之间的关系

时间:2011-05-10 11:35:58

标签: sql sql-server sql-server-2008 sql-server-2000

我有一个小应用程序,用户可以登录并执行他们在那里做的任何事情。关于用户的数据库结构并不奇怪。有三个表:

  • 用户
  • user_group_relation
  • 现在,我如何获得所有组的列表以及一组用户的成员资格状态?

    让我通过一个例子澄清这一点。

    David是'用户''管理员''经济' 的成员 Erik是'用户',管理员 的成员 Richard是'管理员'的成员
    Lisa是'管理员'的成员'经济'

    以下是我希望从sql-query

    获得的结果
    GroupName.......................isEveryoneAMember
    
    users   ......................  someAre  
    Administrators..........        yes  
    Economy ..................      someAre  
    Sales   ....................... no
    

    3 个答案:

    答案 0 :(得分:1)

    SELECT  g.name,
            CASE
            WHEN mcount = 0 THEN
                    'none'
            WHEN mcount = ucount THEN
                    'all'
            ELSE
                    'some'
            END AS isEveryOneAMember
    FROM    (
            SELECT  COUNT(*) AS ucount
            FROM    users
            ) u
    CROSS JOIN
            (
            SELECT  group_id,
                    COUNT(*) AS mcount
            FROM    user_group_relation ug
            GROUP BY
                    group_id
            ) ug
    JOIN    groups g
    ON      g.id = ug.group_id
    

    答案 1 :(得分:0)

    select g.GroupName,
        case
            when count(ug.userId) = (select count(*) from users) then 'yes'
            when count(ug.userId) = 0 then 'no'
            else 'someAre'
        end as HowMany
    from Groups g
    join UserGroups ug on g.id = ug.groupId
    group by g.groupName
    

    答案 2 :(得分:0)

    假设没有重复的组名:

    WITH rollcall AS (
      SELECT
        g.name,
        ug.user_id
      FROM groups g
        CROSS JOIN users u
        LEFT JOIN user_group_relation ug ON g.id = ug.group_id AND u.id = ug.user_id
    )
    SELECT
      GroupName = name,
      isEveryoneAMember = CASE COUNT(user_ud)
        WHEN 0        THEN 'No'
        WHEN COUNT(*) THEN 'Yes'
        ELSE 'someAre'
      END
    FROM rollcall
    GROUP BY name