如果重复记录具有特定值

时间:2016-02-23 18:43:32

标签: sql sql-server-2012

我有一张有特定角色的用户表。对于他们拥有的每个角色,用户一次进入表中。我需要计算具有某些角色的所有用户,但我需要排除任何具有其他角色的重复记录。以下是我的表格中填充的内容

Name   Role
Steve  ROLE_8
Steve  ROLE_9
Steve  ROLE_1

这是我必须选择具有特定角色的用户的查询。我需要做的是检查一个用户是否有ROLE_1,还要检查是否有另一个具有我不想包含的角色的用户实例,并从退货集中排除该用户。

SELECT COUNT(DISTINCT c.user_id)
FROM users c
WHERE email_addr != ''
AND email_addr IS NOT NULL
AND EXISTS
(SELECT r.role_id
 FROM ROLE r, user_role ur
 WHERE c.user_id = ur.user_id
   AND ur.role_id = r.role_id
   AND (r.name = 'ROLE_1'
        OR r.name = 'ROLE_2'
        OR r.name = 'ROLE_3'
        OR r.name = 'ROLE_4'
        OR r.name = 'ROLE_5'
        OR r.name = 'ROLE_6'))

3 个答案:

答案 0 :(得分:1)

使用DISTINCT中的COUNT会导致EXISTS不必要 - 您可以加入user_role表。此时,您只需要排除那些也有您不想要的角色的用户:

SELECT
    COUNT(DISTINCT U.user_id)
FROM
    Users U
INNER JOIN User_Role UR ON UR.user_id = U.user_id AND
INNER JOIN Role R ON
    R.role_id = UR.role_id AND
    R.name IN ('ROLE_USER_ADMIN', 'ROLE_1'...)
WHERE
    U.email_addr IS NOT NULL AND U.email_addr <> '' AND
    NOT EXISTS
    (
        SELECT *
        FROM
            User_Role UR2
        INNER JOIN Role R2 ON
            R2.role_id = UR2.role_id AND
            R2.name IN ('Some_Excluded_Role')
        WHERE
            UR2.user_id = U.user_id
    )

如果您要排除列表之外任何角色的用户,则可以执行以下操作:

SELECT
    COUNT(DISTINCT U.user_id)
FROM
    Users U
INNER JOIN User_Role UR ON UR.user_id = U.user_id AND
INNER JOIN Role R ON
    R.role_id = UR.role_id AND
    R.name IN ('ROLE_USER_ADMIN', 'ROLE_1'...)
WHERE
    U.email_addr IS NOT NULL AND U.email_addr <> '' AND
    NOT EXISTS
    (
        SELECT *
        FROM
            User_Role UR2
        INNER JOIN Role R2 ON
            R2.role_id = UR2.role_id AND
            R2.name NOT IN ('ROLE_USER_ADMIN', 'ROLE_1'...)
        WHERE
            UR2.user_id = U.user_id
    )

答案 1 :(得分:0)

我相信这会让你得到你正在寻找的东西(不知道你期望结果如何)。这个概念首先要找到与“好”相匹配的产品。角色,然后与其他子过滤选择那些也有“坏”的角色。作用。

SELECT COUNT(DISTINCT c.[user_id])
FROM users AS c
    INNER JOIN user_role AS ur
        ON ur.[user_id] = c.[user_id]
WHERE c.email_addr != ''
    AND c.email_addr IS NOT NULL
    AND ur.role_id IN 
        (SELECT sub_r.role_id
        FROM [role] AS sub_r
        WHERE sub_r.name IN ('ROLE_USER_ADMIN', 'ROLE_1')
        )
    AND c.[user_id] NOT IN 
        (SELECT sub2_ur.[user_id]
        FROM user_role AS sub2_ur
            INNER JOIN [role] AS sub2_r
                ON sub2_r.role_id = sub2_ur.role_id
        WHERE sub2_r.name IN ('ROLE_NOT_TO_USE','ANOTHER_NOT_TO_USE')
            AND sub2_ur.[user_id] = c.[user_id]
        )

答案 2 :(得分:0)

如果我想获得一个数据集,其中我包括具有角色1,2或3的用户,并且我想要排除具有角色4和5的用户,我会执行以下操作,如果& #34;名称&#34;是独一无二的:

SELECT COUNT(DISTINCT Name)
FROM ROLE
WHERE Role IN ('ROLE_1','ROLE_2','ROLE_3')
AND Name NOT IN (SELECT DISTINCT Name FROM ROLE WHERE Role IN ('ROLE_4','ROLE_5');