没有GROUP BY的MS Access SQL总和

时间:2018-08-07 10:41:41

标签: sql database ms-access

我试图将Sum“字段”添加到SELECT查询中,在其中将该行上的数据求和,并将其作为字段返回。问题似乎在于我似乎必须使用的GROUP BY语句。使用此功能时,它会将“总和”分组在一起,而不是为每一行数据提供总计。

SELECT PS_DB.TeamName AS [Team Name], TM_adjData.SM_adjName AS Adjudicator, PS_DB.WeekEnding AS [Week Ending], PS_DB.Pts AS [BAU Points], PS_DB.Adhc, Sum(PS_DB.Pts + PS_DB.Adhc) as [Total], PS_DB.Approved AS Approved
FROM PS_DB
LEFT JOIN TM_adjData on PS_DB.Adjudicator = TM_adjData.SM_empNum
GROUP BY TeamName, SM_adjName, WeekEnding, Pts, Adhc, Approved

这将返回518行,就好像我删除了GROUP BY部分和'sum'字段一样,它返回了1,608行(正确)。

如何获取1,608行及其旁边的总和?

2 个答案:

答案 0 :(得分:0)

我认为您可以使用相关的子查询来完成您想做的事情:

SELECT p.TeamName AS [Team Name], a.SM_adjName AS Adjudicator, 
       p.WeekEnding AS [Week Ending], p.Pts AS [BAU Points], p.Adhc,
       (SELECT SUM(p2.Pts + p2.Adhc)
        FROM PS_DB as p2
        WHERE p2.TeamName = p.TeamName  -- perhaps more conditions are needed
       ) as [Total],
       p.Approved AS Approved
FROM PS_DB as p LEFT JOIN
     TM_adjData as a
     ON p.Adjudicator = a.SM_empNum;

答案 1 :(得分:0)

如果要对每一行执行求和,则不对行进行分组,而只是执行加法。我添加了Nz()函数以正确解决添加的任何值均为null并将其视为0的问题:

SELECT 
  PS_DB.TeamName AS [Team Name], 
  TM_adjData.SM_adjName AS Adjudicator, 
  PS_DB.WeekEnding AS [Week Ending], 
  PS_DB.Pts AS [BAU Points], 
  PS_DB.Adhc, 
  Nz(PS_DB.Pts,0) + Nz(PS_DB.Adhc,0) as [Total], -- this is your row sum
  PS_DB.Approved AS Approved
FROM PS_DB
LEFT JOIN TM_adjData on PS_DB.Adjudicator = TM_adjData.SM_empNum

SUM是一个聚合函数,它适用于整个表或数据组(使用GROUP BY)。