select top(10) sb.Id
,sum(tspi.[1]) as TotalForEndowment -
,sum(tspi.[2]) as TotalForEndowment
from dbo.SocialSecurityBills sb
left join
(select * from
(select *from [dbo].[SocialSecurityBillItems] where IsDeleted=0) tspipivot
Pivot(sum( tspipivot.costP) for tspipivot.schemeItemType in
([1],[2])
) as tspipivot
) as tspi on tspi.SocialSecurityBillId=sb.Id
where 1=1
and sb.IsDeleted=0