如何计算外部申请和分组依据的百分比?

时间:2019-04-26 01:19:50

标签: sql group-by percentage outer-apply

我有两个用外部应用程序联接的表。我遇到的问题是我想根据左表中的值(即下面代码中的表A)计算百分比。

尝试作为子选择,但由于分组依据而无法使用

    Select 
    ISNULL(P.div,'GL')Div,
    Right(T.Account,9)Account, FORMAT(T.Accounting_Date,'yyyy-MM') AS Period, 
  Round(Sum(T.Debit+T.Credit),2)Amount
    ,(
            Sum((T.Debit+T.Credit))* 100 / 
                    (Select Sum(T.Debit+T.Credit) 
                        From TABLE_ A 
                        Where Left(T.Account,4) = '9140'
                        Group by Left(T.Account,4) 
                    )
                ) as Perc3nt

    From TABLE_ A AS T
    OUTER APPLY 
        (   Select Vendor, Invoice, Amount,expense_account,Accounting_Date, Dist_Seq, 
            Case When Substring(Expense_Account,6,3) Between '200' and '300' Then 'RES'
                 When Substring(Expense_Account,6,3) >= '500' Then 'COM'
                 When Substring(Expense_Account,6,3) = '100' Then 'CORP'
                 End As Div
            FROM TABLE_ B
            Where T.Vendor = Vendor and T.AP_Invoice = Invoice and Left(T.Account,4) = '9140'
            and T.Invoice_Dist_Seq = Dist_Seq
        )   AS P
    Where Right(Account,9) IN ('1110.0130') and LEFT(T.Account,4) = '9140'
    and T.Accounting_Date >= '03/01/19' and T.Accounting_Date <= '3/31/2019' 

    Group By ISNULL(P.div,'GL'),
             Right(T.Account,9),
             FORMAT(T.Accounting_Date,'yyyy-MM')

Results without the percentage query

0 个答案:

没有答案