根据来自两个来源的列数据计算SUM

时间:2015-06-17 17:56:49

标签: sql-server tsql

我希望有人可以帮我解决这个问题。我试图根据匹配ID来计算费率;但是,我可以从两个地方中的一个获得匹配ID,也可以为NULL。您可以从下面的示例中看到,正在发生的事情是NULL行项目包含在f.matchID计算中。如何将这些NULL行自行计算,而不是包含在f.matchID或g.matchID总和中?您可以提供的任何帮助将不胜感激。谢谢!

SELECT 
    c.[Corp]
   ,b.[FGN_Key]
   ,b.[ACP_Key]
   ,case when f.[matchid] is null then g.[matchid] else f.[matchid] end "MatchID"
   ,case when f.[RuleBaseId] is null then g.[RuleBaseId] else f.[RuleBaseId] end "RuleID"
   ,case when f.[Pass] is null then g.[Pass] else f.[Pass] end  "Pass"
   ,isnull(e.[DWELL],'') "Dwell"
   ,isnull(d.[DCNT],'') "CDU"
   ,b.[Service]
   ,c.[TrueRateCode]
   ,b.[Retail_Rate]
   --,sum(b.[Retail_Rate]) over (partition by f.[matchid]) 
   ,case when f.[matchid] is null then sum(b.[Retail_Rate]) over (partition by g.[matchid]) else sum(b.[Retail_Rate]) over (partition by f.[matchid]) end "Total by Combo"
   --,c.[TrueCodeLength]
   ,c.[RateCnt]
   ,c.[outlet_no]
   ,cast([StartDate] as date) "StartDate"
   ,cast([StopDate] as date) "StopDate"
   ,c.[PromoCode]
   ,cast([DiscountStrtDate] as date) "DiscStartDate"
   --,c.[T30_Rate]
   --,c.[XTrailer_Amt]
   ,isnull(c.[non_std_flag],'') non_std_flag
   ,c.[ReferenceNumber]
FROM 
   [trn].[rate_compare_foreign] b
   left join [site].[tmp_Foreign_Rate_Codes] c on b.ACP_Key = c.[CSGSubscriber] and b.[service] = c.[FullServCode]
   left join [amdocs7_6].[CF000T] d on c.[Corp] = d.[Corp] and c.[House] = d.[House] and c.[Cust] = d.[Cust] and [DCNT] = '6'
   left join [amdocs7_6].[HF000T] e on c.[Corp] = e.[Corp] and c.[House] = e.[House] and c.[Cust] = e.[Cust] and e.[DWELL] in ('0','1','2','3','4','5','7','8','A','B','C','D','F','I','J','K','L','M','N','O','P','Q','R','W')
   left join [ruleng].[breadcrumb] f on c.[corp] = f.[prtnid] and c.[house]+c.[cust] = f.[group0] and c.[id] = f.[factid]
   left join [ruleng].[breadcrumb_item_lob] g on c.[corp] = g.[prtnid] and c.[house]+c.[cust] = g.[group0] and c.[id] = g.[factid]
WHERE 
   ACP_Key = @key
   and [Service] <> 'STMT'
ORDER BY
   f.[matchid]
   ,g.[matchid] 
   ,f.[RuleBaseId]
   ,g.[RuleBaseId]
   ,b.[Service]

我无法附上照片,因为我没有足够的分数(无论这意味着什么)所以我只需要尝试口头给你一个例子。

匹配ID - NULL 价格 - -5.00 当前总和 - 34.99(s / be -5.00)

f.Match ID - 1 价格 - 19.96,25.03,-5.00 当前太阳总计 - 39.99(s / be 39.99)

f.Match ID - 2 费率 - 0.00 当前太阳总计 - 0.00(s /是0.00)

g.Match ID - 3 费率 - 10.00 当前太阳总计 - 10.00(s /是10.00)

1 个答案:

答案 0 :(得分:0)

我会为每个总和创建一个子查询,只是总和的列和记录分组的ID。

在测试总和并且您知道正确之后,请在完整查询中将查询用作子查询。这将隔离每个表的总和。

总和需要记录按正确的信息分组。