2015-11-04 41 views
1

我有两个查询下面的工作,第一个与嵌套选择语句,第二个稍微好一点:替换2选择左加入+计数在不同的表。然而,对于最后一个值(“Existing”),我无法设法对项目中的项目(父 - 子关系)执行联接。有一个更好的方法吗?SQL Server - 通过在同一个表上加入替换嵌套选择计数

查询1

select distinct 
     i.Id 
    , i.Code 
    , (select count(*) from operations o where o.itemid = i.id and o.operationtypeid = 10) "Added" 
    , (select count(*) from operations o where o.itemid = i.id and o.operationtypeid = 20) "Removed" 
    , (select count(*) from items ic where ic.ParentItemId = i.id) - (select count(*) from operations o where o.itemid = i.id and o.operationtypeid = 20) "Existing" 

from items i 

查询2

select distinct 
     i.id 
    , i.code 
    , count(case when o.OperationTypeId = 10 and o.ItemId = i.Id then 1 end) Added 
    , count(case when o.OperationTypeId = 20 and o.ItemId = i.Id then 1 end) Removed 
    , (select count(*) from items ic where ic.ParentItemId = i.id) 
    - count(case when o.OperationTypeId = 20 and o.ItemId = i.Id then 1 end) -- this is what I would like to improve 

from items i 
    left join operations o on o.ItemId = i.Id 

group by i.id, i.code 
+1

这里是一个开始的好地方。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –

+0

猜测:'计数(o.OperationTypeId = 20时的不同情况, o.ItemId = i.Id然后o.ItemId结束)' – shawnt00

回答

0

改变我原来的基于CTE-想法 - 请与您的数据检查,你可能需要使用DISTINCT,在过去数( )或者您可能需要删除它并更新GROUP BY:

SELECT 
    i.id, 
    i.code, 
    count(CASE WHEN o.OperationTypeId = 10 AND o.ItemId = i.Id THEN 1 END) Added, 
    count(CASE WHEN o.OperationTypeId = 20 AND o.ItemId = i.Id THEN 1 END) Removed, 
    count(DISTINCT ic.Id) - count(CASE WHEN o.OperationTypeId = 20 AND o.ItemId = i.Id THEN 1 END) Existing 
FROM items i 
LEFT JOIN operations o 
    ON o.ItemId = i.Id 
LEFT JOIN items ic 
    ON ic.ParentItemId = i.id 
GROUP BY i.id, 
    i.code 
+0

我明白了,但你仍然有2个选择。我想在这种情况下无法避免这种情况,即使性能可能会更好。 'HierarchyCTE.ItemsCnt'也是无效的(不在聚合或分组中),但是因为你无法测试,所以没关系。谢谢! – supafly

+0

O ...对不起,在一分钟内更新另一个想法... –

+0

完成,请让我知道,如果这将适用于你。 –