SQL Sorting by Non-Aggregate Field

Kmcnet 1,256 Reputation points
2025-12-18T22:02:10.35+00:00

Hello everyone and thank for the help in advance. I have a SQL Server table that tracks incoming phone calls with the phone number and time entered. I want to create a query where I can also retrieve a count of the number of times a phone called, but sort the table by the call time. I tried the following:

Select Count(*) as occurrence_count, Caller, TimeEntered from tbl_Log_InboundCalls 
	Group By Caller
	Order By TimeEntered Desc

but I receive the error message "Column 'tbl_Log_InboundCalls.TimeEntered' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." When I add TimeEntered as a Group By, the query does not return the correct data.

I can't figure out how to correct this problem. Any help would be appreciated.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 82,146 Reputation points Volunteer Moderator
    2025-12-19T17:28:57.4033333+00:00

    in group by all columns not included in the group by must be a aggregate so there is only one row per column. You could use max() or min(). If you need a row for each time, then add to group by.

    0 comments No comments

  2. Viorel 125.8K Reputation points
    2025-12-19T18:08:11.5866667+00:00

    Try this too:

    select count(*) over (partition by [Caller]) as [Count], [Caller], TimeEntered 
    from tbl_Log_InboundCalls
    order by TimeEntered desc
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.