/****** Object: View [dbo].[vMsAppUsed] Script Date: 11/20/2013 17:12:14 ******/ 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 17:12:15 ******/ 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 convert(numeric(18,6),[weight]) else 0.000000 end selected , case cancellation when 1 then convert(numeric(18,6),[weight]) else 0.000000 end used from import_appstate) T1 group by T1.app_id)T2 on T2.app_id=ap.id)T3 GO select * from [vMsAppUsed] /* select ap.id app_id,ap.[weight] appweight , convert(numeric(18,6),T1.used ) used, convert(numeric(18,6),T1.selected ) selected from import_approval ap left join (select app_id ,sum(at.[weight]/1000) as used,0 as selected from import_appstate at where cancellation=1 group by app_id union all select app_id ,0 as used,sum(at.[weight]/1000) as selected from import_appstate at where cancellation=0 group by app_id ) T1 on T1.app_id=ap.id*/ --select * from [vMsAppUsed]