sql - 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
解决方案
您可以使用group by
and执行此操作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
查询中不需要 。
推荐阅读
- python - sklearn 的 MLP predict_proba 函数在内部是如何工作的?
- azure - Azure - 为更新管理创建部署
- rust - 从 TlsStream 读取
在 Rust 中使用 `tokio-rustls` - javascript - 为什么我们需要在 react 中绑定事件处理程序
- javascript - 如何修复 TypeError:将循环结构转换为 JSON
- javascript - 为什么上下文未定义
- angularjs - AngularJS 服务不是单例的
- c# - 使用 Microsoft.Web.Administration 将应用程序池添加到 iis C#
- c - gtk3:如何将关键事件/加速器(快捷方式)从本地传播到全球?
- angular - 基于另一个材料复选框更新的复选框