简体   繁体   中英

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. The problem seems to lie with the GROUP BY statement, that I seemingly have to use. 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).

How can I get the 1,608 rows with the sum next to it?

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:

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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