Link to home
Start Free TrialLog in
Avatar of Dale Fye
Dale FyeFlag for United States of America

asked on

Each Group By expression must contain at least one column that is not an outer reference

WHen running the following query, I get the error message above:

Declare @ProgramID int
Declare @CountyID int
Declare @ReferralID int
Declare @StartDate date
Declare @EndDate date
Declare @WorkerType nvarchar(20)

Set @ProgramID = 11
SET @CountyID = 25
set @ReferralID = 8441 
Set @StartDate = '2017-01-01'
Set @EndDate = '2017-01-31'
Set @WorkerType = 'Worker'

SELECT CBI.ProgramID
, CBI.CountyID
, SC.CountyName
, CBI.ReferralID
, R.ReferralName 
, Format(@StartDate, 'mm/dd/yyyy') + ' - ' + Format(@EndDate, 'mm/dd/yyyy') as SvcDates

, Max(CBI.Supervisor) as Supervisor
, Max(CBI.TeamLeader) as TeamLeader

FROM dbo.vw_ContactsBasicInfo_PivotedOnStaffType as CBI
LEFT JOIN dbo.tblFPContacts as C ON CBI.ContactID = C.ContactID 
LEFT JOIN dbo.tblStateCounties as SC on CBI.CountyID = SC.tblCountyID
LEFT JOIN dbo.tblFPReferrals as R on CBI.ReferralID = R.ReferralID 

WHERE (CBI.[Admin] is null)
AND (CBI.ProgramID = @ProgramID)
AND (CBI.CountyID = @CountyID)
AND (CBI.ReferralID = @ReferralID)
AND (C.ContactDate >= @StartDate)
AND (C.ContactDate < DateAdd(day, 1, @EndDate))

Group by CBI.ProgramID
, CBI.CountyID
, SC.CountyName
, CBI.ReferralID
, R.ReferralName 
, Format(@StartDate, 'mm/dd/yyyy') + ' - ' + Format(@EndDate, 'mm/dd/yyyy')

Open in new window


The query, when run without the GroupBy and the two MAX() statements runs properly.
ASKER CERTIFIED SOLUTION
Avatar of Jeff Tennessen
Jeff Tennessen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Scott Pletcher
Get rid of lines 39 and 41; besides, you don't need them anyway, since the CountyID and ReferralID represent the same data:

Group by CBI.ProgramID
, CBI.CountyID
/*, SC.CountyName*/
, CBI.ReferralID
/*, R.ReferralName */
, Format(@StartDate, 'mm/dd/yyyy') + ' - ' + Format(@EndDate, 'mm/dd/yyyy')
Avatar of Dale Fye

ASKER

@Jeff,

That worked, although I would have expected to receive a message stating that that line could not be in the SELECT clause if not included in an aggregate function or in the group by clause.
Hey @Dale, that line contained only "static" data that didn't change from record-to-record, so it didn't need to be aggregated. Does that make sense?
Yes, Jeff, that makes sense.