我怎样才能从sql表中减去数据

时间:2014-03-25 14:44:48

标签: sql-server group-by subtraction

如何根据AccountGroupId 4 - AccountGroupId 5

减去两列
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

1 个答案:

答案 0 :(得分: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

它将月份和年份加入两个派生表作为收入和支出