如何按帐户代码长度汇总帐户?

时间:2012-04-26 07:24:06

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

我有2个表:DimAccounts和FactBudget。

DimAccounts示例:

AccountKey  AccountCode     AccountName AccountGroup    AccountType
1.6 1         6 1               NN          6               S
1.6 10        6 10              MMM         6               S
1.6 101       6 101             TTT         6               S
1.6 1010      6 1010            IIII        6               B
1.6 1011      6 1011            OOOO        6               B
1.6 1012      6 1012            KKK         6               B

FactBudget示例:

TimeKey    AccountKey   Debit   Credit
20110719    1.6 1010    20.00   5.00
20110719    1.6 1011    15.00   0.00
20110719    1.6 1000    5.00    0.00
20110719    1.6 1012    10.00   5.00
20110719    1.6 1112    10.00   0.00

在FactBudget中有许多只有B类的账户。我需要获得账户类型S(总和)的借方和贷方和。

示例数据的解决方案示例:

TimeKey   AccountKey   Debit    Credit
20110719    1.6 1     60.00    10.00
20110719    1.6 10    50.00    10.00
20110719    1.6 101   45.00    10.00

要计算总帐科目1.6 101(带有空格的7个符号)的借方和贷方,我们需要将所有实际预算中的所有累计子串起来最多7个符号(1.6 1012 - > 1.6 101,1.6 1112 - > 1.6 111,1.6 1011 - > 1.6 101)然后它们在哪里相等 (1.6 101 = 1.6 101)按时间键和借方和贷方分组。

要计算总帐户1.6 1(带有空格的5个符号)的借方和贷方,我们需要将实际预算中的所有累计子串起来最多5个符号(1.6 1012 - > 1.6 1,1.6 1112 - > 1.6 1,1.6 1011 - > 1.6 1)然后它们在哪里相等 (1.6 1 = 1.6 1)按时间键和借方和贷方分组:)等等。

那么,如何通过TimeKey和AccountKey获得S账户借方和贷方总和?

3 个答案:

答案 0 :(得分:1)

基本上,您可以使用this answer并只更改其中一个连接条件:

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 LIKE s.AccountCode + '%'
  /* alternatively: ON s.AccountCode = LEFT(b.AccountCode, LEN(s.AccountCode)) */
  INNER JOIN FactBudget  f ON f.AccountKey = b.AccountKey
WHERE s.AccountType = 'S'
  AND b.AccountType = 'B'
GROUP BY
  f.TimeKey,
  s.AccountKey

答案 1 :(得分:1)

SELECT      F.TimeKey,
            D.AccountKey,
            SUM(F.Debit) Debit,
            SUM(F.Credit) Credit
FROM        DimAccounts D
INNER JOIN  FactBudget F ON F.AccountKey LIKE D.AccountKey + '%'
WHERE       D.AccountType = 'S'
GROUP BY    F.TimeKey,
            D.AccountKey

答案 2 :(得分:0)

也许是这样的:

SELECT
    FactBudget.TimeKey,
    DimAccounts.AccountKey,
    SUM(FactBudget.Debit) AS Debit,
    SUM(FactBudget.Credit) AS Credit
FROM
    DimAccounts
    JOIN FactBudget
        ON DimAccounts.AccountKey=
           SUBSTRING(FactBudget.AccountKey,0,DATALENGTH(DimAccounts.AccountKey)+1)
WHERE
    DimAccounts.AccountType='S'
GROUP BY
    FactBudget.TimeKey,
    DimAccounts.AccountKey