sql-server 添加自定义布尔值列,其中数据基于链接实体的值进行计算

h43kikqp  于 2022-10-31  发布在  其他
关注(0)|答案(1)|浏览(123)

我有两张table:EntityEntityItem中的一个或多个。
EntityItems表具有Reason列,该列是可空枚举。
我试图写一个视图,它将返回一些Entitity的列,另外还有一个布尔列,说明是否所有对应的EntityItem.Reason都有一个非空值。
下面的查询返回了我所需要的一些信息:

SELECT EntityItem.Id, COUNT(EntityItem.Reason) As Test
FROM EntityItem
GROUP BY EntityItem.ParentEntityId
ORDER BY Test DESC

输出示例:

Id             Test
132189         4
132190         2
132197         1
1              0
2              0
3              0
4              0
5              0
6              0

但是,当我尝试将其添加到最终查询中时,每个EntityItem都有重复的行

SELECT [Entity].[Id],
       ...
        (SELECT CASE WHEN (SELECT COUNT([EntityItem].[Reason]) FROM [EntityItem] WHERE [EntityItem].[ParentEntityId] = [Entity].[Id]) = 0
        THEN 0
        ELSE 1
        END) AS Test
FROM [Entity]
  ...
  LEFT JOIN [EntityItem] ON [Entity].[Id] = [EntityItem].[ParentEntityId]

输出示例:

Id             Test
1              1
1              1
2              0
2              0
2              0
2              0
3              1
3              1
4              0

问题1:我的方法正确吗?
问题2:有没有办法在没有DISTINCT的情况下删除重复的行?

n9vozmp4

n9vozmp41#

对于第二个查询,您需要在连接之前 * 进行聚合,例如,使用 outer apply,如下所示:

select e.Id, 
  case when i.cnt = 0 then 0 else 1 end as Test
from Entity e
outer apply (
    select Count(Reason) cnt
    from EntityItem i
    where i.ParentEntityId = e.Id
)i;

也就是说,由于如果计数大于0,则返回值总是1,因此实际上不需要计算任何值:

select e.Id, 
  case when exists (
    select * from EntityItem i 
    where i.ParentEntityId = e.Id
  ) 
  then 1 else 0 end as Test
from Entity e;

相关问题