如何汇总账户

时间:2012-04-19 17:20:20

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我有3个表:DimAccounts,DimTime和FactBudget。

DimAccounts示例:

AccountKey  Accouncode  AccountType   AccountFrom   AccountTo 
1.10001     10001       S                  11401    27601
1.10002     10002       S                  11401    16501
1.11000     11000       S                  11401    11508
1.110001    110001      B                   NULL    NULL
1.110002    110002      B                   NULL    NULL
1.11400     11400       S                  11401    11408

DimTime示例:

   TimeKey      FullDate
    20020102    2002-01-02
    20020103    2002-01-03
    20020104    2002-01-04

FactBudget示例:

TimeKey     AccountKey              Debit    Credit
20080523    1.110002                0.00    884.00
20080523    1.110001                0.00    4251.96
20100523    1.100002                229.40  0.00
20080523    1.100002                711.79  0.00
20090523    1.110002                0.00    711.79
20080523    1.110001                0.00    229.40
20040523    1.100002                0.00    15619.05

在FactBudget中有许多只有B类的账户。我需要计算账户类型为S(总和)的借方和贷方和。列AccountFrom和AccountTo显示B类型帐户从何处开始汇总(AccountFrom)和结束(AccountTo)。

我使用游标制作了解决方案....但是你知道这非常糟糕:)我认为在某种程度上可以在FactBudget中分组数据(因为在事实预算和行600k中也有很多列)以及搜索解决方案时(当我组只离开了6万行):

SELECT [TimeKey], 
       [AccountKey], 
       SUM([Debit]), 
       SUM([Credit]) 
FROM   [Interlux].[dbo].[FactBudget] 
GROUP  BY [TimeKey], 
          [AccountKey] 

那么,如何通过TimeKey和AccountKey获得S账户借方和贷方总和? (AccountKey数据类型为nvarchar)

解决方案示例:

TimeKey     AccountKey  Debit    Credit
20080523    1.10002     0.00    2500
20080523    1.11000     0.00    8000
20080524    1.10002     900  0.00

在事实预算中,没有类型为S的帐户!!!!我们需要得到它(例如1.11000仅适用于日期20080523):

select 
SUM(Debit), SUM(Credit)
from FactBudget
LEFT JOIN [DimAccounts]
ON [DimAccounts].[AccountKey] = FactBudget.[AccountKey]   
where CAST([DimAccounts].AccountCode AS INT) >=11401    
and CAST([DimAccounts].AccountCode AS INT) <= 11508
and FactBudget.Timekey = 20080523

但我需要每个S帐户借记和按日汇总和。

2 个答案:

答案 0 :(得分:0)

SELECT a.TimeKey, a.AccountKey, SUM(a.Debit) AS 'DebitSum', SUM(a.Credit) AS 'CreditSum'
FROM FactBudget a
JOIN DimAccounts b on b.AccountKey = a.AccountKey
WHERE b.AccountType='S'
GROUP BY a.AccountKey, a.TimeKey

这是你要找的吗?

答案 1 :(得分:0)

据我所知,您需要将DimAccounts加入到自身,以将B类帐户与其对应的S类帐户相关联,然后将该行集加入FactBudget以最终获得数据。像这样:

SELECT
  f.TimeKey,
  s.AccountKey,
  SUM(f.Debit) AS Debit,
  SUM(f.Credit) AS Credit
FROM DimAccounts s
  INNER JOIN DimAccounts b ON b.AccountCode BETWEEN s.AccountFrom AND s.AccountTo
  INNER JOIN FactBudget  f ON f.AccountKey = b.AccountKey
WHERE s.AccountType = 'S'
  AND b.AccountType = 'B'
GROUP BY
  f.TimeKey,
  s.AccountKey