简体   繁体   English

没有GROUP BY的MS Access SQL总和

[英]MS Access SQL Sum without GROUP BY

I am trying to add a Sum 'field' to a SELECT query, where it sums up the data on that row, and returns it as a field. 我试图将Sum“字段”添加到SELECT查询中,在该字段中求和该行上的数据,并将其作为字段返回。 The problem seems to lie with the GROUP BY statement, that I seemingly have to use. 问题似乎在于我似乎必须使用的GROUP BY语句。 When using this, it groups the 'sums' together, rather than provides a total for each row of data. 使用此功能时,它将“和”分组在一起,而不是为每一行数据提供总计。

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

This returns 518 rows, where as if I remove the GROUP BY section and the 'sum' field, it returns 1,608 rows (which is correct). 这将返回518行,就好像我删除了GROUP BY部分和'sum'字段一样,它返回了1,608行(正确)。

How can I get the 1,608 rows with the sum next to it? 我怎样才能得到1,608行及其旁边的总和?

I think you can do what you want with a correlated subquery: 我认为您可以使用相关的子查询来完成您想要的事情:

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;

If you want to perform a sum for each row, you don't group rows, instead you simply perform addition. 如果要对每一行执行求和,则不对行进行分组,而只是执行加法。 I've added Nz() function to properly address issue where any of the value being added is null and treat it as 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 is an aggregate function and it works on entire table or groups of data (with GROUP BY ). SUM是一个聚合函数,它适用于整个表或数据组(使用GROUP BY )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM