我需要总计total_Amount,其中title = income和title = expense

时间:2016-07-06 18:58:50

标签: sql c#-3.0

我需要根据标题加总total_amount。实际上我没有这两个表之间的关系,但要取出保存我需要总结它们和差异两个总和的总和。

ALTER PROCEDURE [dbo].[SpSavingDetail]
@year varchar(10),
@month varchar(10)
AS
BEGIN

SET NOCOUNT ON;

declare @Saving int 

select e.Date_time as Date_time ,c.category as Particular,e.Description as Description ,e.Amount as Amount,
e.Frequency as Frequency,e.Total_Amount as Total_Amount,'Expense' as Title from tbl_expense as e
left join tbl_category as c on c.Cat_id=e.Cat_id where datepart(MM,e.Date_time)=@month and datepart(YYYY,e.Date_time)=@year
union 
select i.Date_time as Date_time ,s.source  as Particular,i.Description as Description ,i.Amount as Amount,
i.Frequency as Frequency,i.Total_Amount as Total_Amount,'Income' as Title from tbl_income as i
left join tbl_source as s on s.Source_id=i.Source_id
 where datepart(MM,i.Date_time)=@month and datepart(YYYY,i.Date_time)=@year





  [1]: http://i.stack.imgur.com/8Z5po.jpg

1 个答案:

答案 0 :(得分:0)

我不知道这种语言,(它是T-SQL吗?如果你更恰当地标记问题,你会有更多的运气)但你应该能够做到以下几点:

declare @expense int 
declare @income int 

select @expense = SUM(e.Amount)
  from tbl_expense as e
 where datepart(MM,e.Date_time)=@month and datepart(YYYY,e.Date_time)=@year

select @income = SUM(i.Amount)
  from tbl_income as i
 where datepart(MM,i.Date_time)=@month and datepart(YYYY,i.Date_time)=@year

@Saving = @income - @expense