我有两个查询下面的工作,第一个与嵌套选择语句,第二个稍微好一点:替换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
这里是一个开始的好地方。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –
猜测:'计数(o.OperationTypeId = 20时的不同情况, o.ItemId = i.Id然后o.ItemId结束)' – shawnt00