gpt4 book ai didi

mysql - Group by select 基于 OR 条件

转载 作者:行者123 更新时间:2023-11-29 14:36:24 25 4
gpt4 key购买 nike

将 UNION 与两个选择查询一起使用后,我得到以下结果

UserId    Name    Status
------ ------ --------
1 User1 Active
2 User2 Active
1 User1 InActive
3 User3 InActive

但预期的结果是

UserId Name Status
---------------------
1 User1 Active
2 User2 Active
3 User3 InActive

我需要的是,我想按列 Id 分组,如果有任何一个结果是事件的,则状态为事件。如何为此形成 SQL 查询?

任何人都可以建议查询以下任何一个数据库吗?

  1. MSSQL
  2. 甲骨文
  3. MySQL
  4. PostgreSQL

编辑:

这是我在 PostgreSQL 中尝试过的查询

(SELECT DISTINCT User.Id,User.DisplayName,AppAccessToUsers.IsActive='1' AND User.IsActive='1' AS IsStatusActive 
FROM Applications Left JOIN AppAccessToUsers ON (Applications.Id=AppAccessToUsers.ApplicationId)
Left JOIN User ON (AppAccessToUsers.UserId=User.Id) WHERE Applications.ClientId='e7e66c1b-b3b8-4ffb-844b-fc4840803265')
UNION
(SELECT DISTINCT User.Id,User.DisplayName,AppAccessToGroups.IsActive='1' AND Group.IsActive='1' AND UserGroup.IsActive='1' AND User.IsActive='1' AS IsStatusActive
FROM Applications Left JOIN AppAccessToGroups ON (Applications.Id=AppAccessToGroups.ApplicationId)
Left JOIN Group ON (AppAccessToGroups.GroupId=Group.Id) Left JOIN UserGroup ON (Group.Id=UserGroup.GroupId)
Left JOIN User ON (UserGroup.UserId=User.Id) WHERE Applications.ClientId='e7e66c1b-b3b8-4ffb-844b-fc4840803265')

最佳答案

使用这个查询,

SELECT  UserId
,Name
,CASE WHEN min(status) = 'Active' THEN 'Active' ELSE 'InActive' END
FROM users GROUP BY UserId,Name

关于mysql - Group by select 基于 OR 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43997720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com