我有两张table:Entity
和EntityItem
中的一个或多个。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
的情况下删除重复的行?
1条答案
按热度按时间n9vozmp41#
对于第二个查询,您需要在连接之前 * 进行聚合,例如,使用 outer apply,如下所示:
也就是说,由于如果计数大于0,则返回值总是1,因此实际上不需要计算任何值: