Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Use of "where" clause based upon sum value

Author  Topic 

snufse
Constraint Violating Yak Guru

469 Posts

Posted - 2009-05-06 : 13:13:43
I need to select records where sum of field dbo.EquipmentlaborEvent.Hours is greater than a set value.

SELECT          dbo.Region.CompanyRegionID as divison, 
dbo.Job.CompanyJobId as job,
dbo.Batch.ReportDate as jobdate,
dbo.Equipment.CompanyEquipmentID as equipmentID,
dbo.Equipment.Name as equipmentname,
sum(dbo.EquipmentLaborEvent.Hours) as hours

FROM dbo.Region
inner join dbo.Batch on dbo.Batch.RegionGuid = dbo.Region.RegionGuid
inner join dbo.Event on dbo.Event.BatchGuid = dbo.Batch.BatchGuid
inner join dbo.Job on dbo.Job.JobGuid = dbo.Event.JobGuid
join dbo.Equipment on dbo.Equipment.JobGuid = dbo.Job.JobGuid
join dbo.EquipmentLaborEvent on dbo.EquipmentLaborEvent.Eventguid = dbo.Event.EventGuid

WHERE dbo.Region.CompanyRegionID = '00032' and
sum(dbo.EquipmentlaborEvent.Hours) <= 50
GROUP BY dbo.Region.CompanyRegionID, dbo.Job.CompanyJobID, dbo.Equipment.CompanyEquipmentID, dbo.Equipment.Name, dbo.Batch.ReportDate
GO


Getting error:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-05-06 : 13:18:45
Use HAVING instead:

HAVING sum(dbo.EquipmentlaborEvent.Hours) <= 50

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page
   

- Advertisement -