/****** Object: View [dbo].[vMsAppUsed] Script Date: 11/20/2013 10:35:28 ******/ IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vMsAppUsed]')) DROP VIEW [dbo].[vMsAppUsed] GO /****** Object: View [dbo].[vMsAppUsed] Script Date: 11/20/2013 10:35:28 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[vMsAppUsed] AS select app_id,appweight,used,selected, appweight-used-usedweight remain, appweight-usedweight-used-selected canbeused from (select ap.id app_id,ap.[weight] as appweight,ap.usedweight, case when selected is null then 0 else selected end selected, case when used is null then 0 else used end used from import_approval ap left join (select T1.app_id,sum(T1.selected) selected,sum(T1.used) used from (select app_id, case cancellation when 0 then [weight] else 0 end selected , case cancellation when 1 then [weight] else 0 end used from import_appstate) T1 group by T1.app_id)T2 on T2.app_id=ap.id)T3 GO