在 SQL 创建临时表时,即使一个相关记录为 TRUE 而其他记录为 FALSE,我如何将所有布尔值设置为 TRUE

In SQL when creating temp tables, how can I set all boolean values to TRUE if even one related record is TRUE but others are FALSE

例如:

Table 1 - 项目

Id Name Master Project Active
1 Project A N
2 Project A - 1 1 Y
3 Project A - 2 1 N
4 Project B N
5 Project B -1 4 N
6 Project C NULL
7 Project C - 1 6 Y

我愿意return |项目|活跃| |-----|----| |项目A |是| |项目B | N| |项目C | Y|

我如何在 SQL 中写这个,这样它基本上...

如果有任何项目处于活动状态(主项目或子项目),则所有项目都处于活动状态 如果所有项目都不活跃,则不活跃 如果主项目为 NULL,请检查相关项目是否处于活动状态。仅 return 返回一条记录。

我在想这会包含一个存在的子查询,但不确定如何构造它。

;WITH MasterProjects as
(
SELECT 
Name, 
CASE 
    WHEN (SELECT COUNT(1) FROM Table1 t2 WHERE t2.Name LIKE t1.Name + '%' AND Active = 'Y') > 0 THEN 'Y' 
    ELSE 'N' END AS Active
FROM Table1 t1
WHERE MasterProject = ''
)
SELECT t1.Id, t1.Name, t1.MasterProject, t2.Active
FROM Table1 t1
JOIN MasterProjects t2 ON t1.Name LIKE t2.Name + '%'

我假设子项目的 isActive 不为 null

这是我的解决方案,使用内部联接 table 和 sum(case when)

id name master_project active
1 Project A N
2 Project A - 1 1 Y
3 Project A - 2 1 N
4 Project B N
5 Project B - 1 4 N
6 Project C
7 Project C - 1 6 Y

加入Table:

select *
from projects tb1
inner join projects tb2 
on tb1.id = tb2.master_project or (tb1.master_project is null and tb1.id = tb2.id)
id name master_project active id name master_project active
1 Project A N 1 Project A
1 Project A N 2 Project A - 1 1 Y
1 Project A N 3 Project A - 2 1 N
4 Project B N 4 Project B N
4 Project B N 5 Project B - 1 4 N
6 Project C 6 Project C
6 Project C 7 Project C - 1 6 Y

这里是final query:

select tb1.name Project, case when sum(case when tb2.active = 'Y' then 1 end ) >= 1 then 'Y' else 'N' end Active
from projects tb1
inner join projects tb2 on tb1.id = tb2.master_project or (tb1.master_project is null and tb1.id = tb2.id)
group by tb1.name

结果:

Project Active
Project A Y
Project B N
Project C Y