我有 2 張桌子:Entity和EntityItem.
EntityItems表有一個Reason可以為空的列舉列。
我正在嘗試撰寫一個視圖,該視圖將回傳一些Entititys 列以及一個布爾列,該列說明所有對應的是否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?
uj5u.com熱心網友回復:
對于您的第二個查詢,您需要在加入之前進行聚合,例如使用外部應用,例如:
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;
話雖如此,由于如果計數大于零,您總是回傳值 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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/521152.html
上一篇:如何使用第一個元素python分組來連接元組中的第二個元素
下一篇:連接來自兩個API回應的資料
