首页 > 解决方案 > SQL 分组依据?需要子选择?

问题描述

我正在寻找具有已注册和未注册用户的所有组。我试图使用 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

标签: sqlsql-server

解决方案


您可以使用group byand执行此操作having

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查询中不需要 。


推荐阅读