在SQL中使用不同的和

时间:2013-08-09 15:57:24

标签: sql

我有一个查询,它返回我正在寻找的数据使用不同的,但是当我对该数据进行求和时,我得到了一个错误的数量,我的层次点'4-2-0-0-5-2'。 4-2-0-0-5-2有多行,所以当我总结它时,它没有正确加起来。将distinct与SUM语句合并的最佳方法是什么。任何帮助都会被贬低。感谢。

首先查询:

     Select distinct B.Proj_Nbr,c.proj_cc,h.proj_cc, h.Proj_Hier, B.Proj_Nm, D.Fscl_Per, A.Amount
     from acct_bal a 
     inner join dim_proj b on a.dim_proj_id = b.dim_proj_id 
     inner join essbase_fcs.projects_hier_map c on c.proj_nbr = b.proj_nbr 
     inner join dim_per_mo d on d.dim_per_mo_id = a.dim_per_mo_id 
     Inner Join Dim_Acct F On A.Dim_Acct_Id = F.Dim_Acct_Id 
     Inner Join Dim_Org G On A.Dim_Org_Id = G.Dim_Org_Id 
     inner join essbase_fcs.projects_hier_map h on h.proj_cc = g.cost_ctr
     inner join dim_org g1 on c.proj_cc = g1.cost_ctr
     Where F.Fin_Lee_Nbr = 500 
     and c.proj_hier like '4-2-0-0-5-2%'
     And A.Dim_Scnro_Id = '45'
     And D.Fscl_Yr = '2014'
    And b.Proj_Nbr = '9005459'
    and fscl_per ='1'

2行的结果:

9005459 0358080 0358080 4-2-0-0-5-2 Global Sales.com (iSell)    179777.09
9005459 0358080 0358057 4-2-0-0-5-5 Global Sales.com (iSell) 2257.3**

当我想要对数据求和时,我使用下面的查询。这给了我正在寻找的两行,但proj_hier 4-2-0-0-5-2有错误的数量,因为它有多行。

 Select  B.Proj_Nbr,c.proj_cc, h.Proj_Hier, B.Proj_Nm, D.Fscl_Per, sum(A.Amount)
     from acct_bal a 
     inner join dim_proj b on a.dim_proj_id = b.dim_proj_id 
     inner join essbase_fcs.projects_hier_map c on c.proj_nbr = b.proj_nbr 
     inner join dim_per_mo d on d.dim_per_mo_id = a.dim_per_mo_id 
     Inner Join Dim_Acct F On A.Dim_Acct_Id = F.Dim_Acct_Id 
     Inner Join Dim_Org G On A.Dim_Org_Id = G.Dim_Org_Id 
     inner join essbase_fcs.projects_hier_map h on h.proj_cc = g.cost_ctr 
     inner join dim_org g1 on c.proj_cc = g1.cost_ctr
     Where F.Fin_Lee_Nbr = 500 
     and c.proj_hier like '4-2-0-0-5-2%'
     And A.Dim_Scnro_Id = '45'
     And D.Fscl_Yr = '2014'
    And b.Proj_Nbr = '9005459'
    and fscl_per ='1'
    group by B.Proj_Nbr,c.proj_cc,f.dim_acct_id, h.Proj_Hier, B.Proj_Nm, D.Fscl_Per
                    having Sum(A.Amount) <> 0 
                   Order By  H.Proj_Hier,  B.Proj_Nbr, D.Fscl_Per

1 个答案:

答案 0 :(得分:0)

请概括问题然后询问,如果我理解你的问题这是解决方案:

一般查询:

从your_table

中选择sum(a.amountColumn)

按agrrColumnName分组;

如果我更改您的查询:

选择不同的B.Proj_Nbr,c.proj_cc,h.proj_cc,h.Proj_Hier,B.Proj_Nm,D.Fscl_Per, sum(A.Amount)      来自acct_bal a      内部联接dim_proj b在a.dim_proj_id = b.dim_proj_id上      内部联接essbase_fcs.projects_hier_map c on c.proj_nbr = b.proj_nbr      内部连接dim_per_mo d在d.dim_per_mo_id = a.dim_per_mo_id上      内部连接Dim_Acct F On A.Dim_Acct_Id = F.Dim_Acct_Id      内部连接Dim_Org G On A.Dim_Org_Id = G.Dim_Org_Id      内部联接essbase_fcs.projects_hier_map h on h.proj_cc = g.cost_ctr      c.proj_cc = g1.cost_ctr上的内连接dim_org g1      其中F.Fin_Lee_Nbr = 500      和c.proj_hier一样'4-2-0-0-5-2%'      并且A.Dim_Scnro_Id = '45'      和D.Fscl_Yr ='2014'     并且b.Proj_Nbr ='9005459'     由B.Proj_Nbr提供的fscl_per ='1'组;