sqlgroup-by

ALTERNATE TO SQL GROUPBY (such as to avoid repeating on aggregate fields)


Is there any way to have a query return say 8 fields but only group by one field and perform only one aggregate function on another field? I get an error that suggests that i need to group by by all fields that do not have aggregate functions.

I need to find the number of completed surveys for each month but need to include other information such as session starttime, session status, session id, etc.

When I try to execute this:

SELECT Datepart("m", starttime), 
       COUNT(sessionid), 
       sessionstatus, 
       starttime, 
       endtime, 
       surveyid, 
       surveybook, 
       userdesk 
FROM   survey_sessions 
GROUP  BY Datepart("m", starttime) 

I get the error: "You tried to execute a query that does not include the specified expression 'SessionStatus' as part of an aggregate function"

I do not need any other aggregates and grouping by the remaining fields does not give me ability to get the monthly total.


Solution

  • If you are using a GROUP BY you ALWAYS have to have all of the fields selected included within the GROUP BY no matter what.

    If you include everything in the group by clause you probably aren't going to get the results you were expecting because I'm assuming that every row is pretty much unique when grouping on that many columns.

    Assuming you're using SQL Server could try:

    SELECT Datepart("m", starttime), 
       COUNT(sessionid) OVER(PARTITION BY Datepart("m", starttime)) AS Count, 
       sessionstatus, 
       starttime, 
       endtime, 
       surveyid, 
       surveybook, 
       userdesk 
    FROM   survey_sessions 
    

    This will display the all the information you are looking for with a count of how many occured in the month displayed on each row.

    I'm not 100% sure what you're trying to accomplish so it's hard to be more specific.

    EDIT: Adding alternate solution for access.

    If you need it to work in access as well you could try your you could try the following. Replace the '' with a number, date, or string that corresponds with the data-type the first query returns. This will place rows at the bottom of your query with the total for each month.

    SELECT Datepart("m", starttime), 
       0 AS COUNT
       sessionstatus, 
       starttime, 
       endtime, 
       surveyid, 
       surveybook, 
       userdesk 
    FROM   survey_sessions 
    
    UNION ALL 
    
    SELECT Datepart("m", starttime),
       COUNT(sessionid) as Count,
       '',
       '',
       '',
       '',
       '',
       ''
    FROM survey_sessions
    GROUP BY Datepart("m", starttime)