2014-03-25 26 views
0

我怎麼能減去基於AccountGroupId 4兩列 - AccountGroupId 5我怎麼能減去從SQL表中的數據

I have data like : 

ID  Month  Year AccountGroupName AccountGroupId Balance 

1  February 2014 Expense    5    200 
2  February 2014 Income     4    300 
3  March  2014 Expense    5    250 
4  March  2014 Income     4    200 


Desired Result : 

ID  Month  Year AccountGroupName AccountGroupId Balance 

1  February 2014 Income     4    100 
2  March  2014 Expense    5   -50 

查詢:

IF OBJECT_ID('tempdb..#temptbale') IS NOT NULL DROP TABLE #temptbale 
IF OBJECT_ID('tempdb..#subTable') IS NOT NULL DROP TABLE #subTable 

    SELECT 
    (DATENAME(Month,JD.CreatedDateTime)) as [Month], 
    DATEPART(yyyy ,JD.CreatedDateTime) as [Year], 
    AG.AccountGroupName, 
    AT.AccountGroupID, 
    Sum(A.OpeningBalance) as Balance 
    into #temptbale 
    FROM AccountGroup AG 
    INNER JOIN AccountType AT ON AG.AccountGroupID=AT.AccountGroupID 
    Right join Account A on A.AccountTypeID = AT.AccountTypeID 
    Inner join JournalMasterDetail JD on JD.AccountID = A.AccountID 
    where AG.AccountGroupID > 3 and year(JD.CreatedDateTime) = year(getdate()) 
      and datepart(dy, JD.CreatedDateTime) <= datepart(dy, getdate()) 
    group by 
    A.AccountName, 
    JD.CreatedDateTime, 
    AG.AccountGroupName,  
    A.OpeningBalance, 
    AT.AccountGroupID 



    select ROW_NUMBER() OVER(ORDER BY [Month]) AS 'ID',[Month],[Year],AccountGroupName,AccountGroupID,SUM(Balance)as Balance 
    into #subTable 
    from #temptbale 
    group by 

    [Month], 
    AccountGroupName, 
    AccountGroupID, 
    [Year] 
    order by 
    [Month] 

    select * from #subTable 
+0

你是按AccountGroupName&AccountGroupId分組還是僅僅從每月的收入中扣除費用?因爲你想要的輸出中的數據對我來說不太合適。 – Tanner

回答

0

您可以運行此查詢

select t.Month,t.Year 
,Case when tblExp.Balance > tblIncome.Balance then tblExp.AccountGroupName else tblIncome.AccountGroupName end as AccountGroupName 
,Case when tblExp.Balance > tblIncome.Balance then tblExp. AccountGroupId else tblIncome. AccountGroupId end as AccountGroupId 
,tblIncome.Balance - tblExp.Balance as Balance 
from table t 
inner join(select * from table where AccountGroupId = 4) as tblExp on tblExp.year = t.year and tblexp.Month = t.Month 
inner join(select * from table where AccountGroupId = 5) as tblIncome on tblIncome.year = t.year and tblIncome.Month = t.Month 
group by t.Month,t.Year 

這是加入月份和年份與兩個派生表作爲收入和支出