SQL分组依据?需要子选择吗?

时间:2018-08-21 14:35:04

标签: sql sql-server

我正在寻找具有已注册和未注册用户的所有组。我试图使用Group By,但是我缺少了一些东西。谢谢

Select U.IsRegistered, UG.UserGroupId
From tblGroup G
Join tblUserGroup UG on UG.GroupId = G.GroupId
Join tblUser U on U.UserId = UG.GroupId
Group By U.IsRegistered, UG.UserGroupId

tblUser
-------+----------+-------------
UserId | UserName | IsRegistered
1      | Bob      | 1
2      | Sally    | 0
3      | Jeff     | 1


tblGroup
--------+----------
GroupId | GroupName
1       | Blue
2       | Green


tblUserGroup
------------+---------+-------
UserGroupId | GroupId | UserId
1           | 1       | 1
2           | 1       | 2
3           | 2       | 3

3 个答案:

答案 0 :(得分:3)

您可以使用group byhaving进行此操作:

Select U.IsRegistered, UG.UserGroupId
From tblUserGroup UG Join
     tblUser U
     on U.UserId = UG.GroupId
Group By UG.UserGroupId
Having sum(IsRegistered) > 0 and sum(1 - IsRegistered) > 0;

having子句仅指定至少有一个注册用户和一个非注册用户。

请注意,查询中不需要tblGroup

答案 1 :(得分:0)

SELECT GroupName
From tblGroup G
Join tblUserGroup UG on UG.GroupId = G.GroupId
Join tblUser U on U.UserId = UG.UserID
GROUP BY GroupName
HAVING AVG(cast(IsRegistered as float)) < 1
AND AVG(cast(IsRegistered as float)) > 0

答案 2 :(得分:0)

如果我正确地理解了这一点,则需要满足两个条件。首先,我们需要知道该组具有未注册的用户。其次,我们需要知道该组有一个注册用户。因此,如果我们创建一个具有第一个条件的语句,并将其与具有第二个条件的语句进行内部连接,那将只剩下所需的组。

Select UnRegistered_Group.UserGroupId
From (
    SELECT UG.UserGroupID
    FROM tblGroup G
    INNER Join tblUserGroup UG on UG.GroupId = G.GroupId
    INNER Join tblUser U on U.UserId = UG.GroupId
    WHERE U.IsRegistered = 0
) AS UnRegistered_Group
Inner Join (
    SELECT UG.UserGroupID
    FROM tblGroup G
    INNER Join tblUserGroup UG on UG.GroupId = G.GroupId
    INNER Join tblUser U on U.UserId = UG.GroupId
    WHERE U.IsRegistered = 1
) AS Registered_Group
On UnRegistered_Group.UserGroupID = Registered_Group.UserGroupID;