2012-04-26 50 views
0

我有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个符号与空格),我们需要串中factbudget了所有acounts至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得到的帐目借记卡和中房总和?

回答

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 
+0

作品完美谢谢 – Justin 2012-04-26 08:22:07

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 
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