0
votes
ALTER PROCEDURE Sp_Num_Tracking 
@UserID int

AS
BEGIN
declare @lastLogonDate datetime;
ALTER PROCEDURE Sp_num_Tracking 
@UserID int

AS
BEGIN
declare @lastLogonDate datetime;
declare @CurrentLogonDate datetime;
declare @onemonthtime datetime;
declare @frmbeg int;
declare @oneweektime datetime;

select @lastLogonDate=  max( crimedate) from tblcrime where UserID=@UserID
set @CurrentLogonDate=getdate()
set @onemonthtime=dateadd(mm,-1,@CurrentLogonDate)
set @oneweektime=dateadd(dd,-7,@CurrentLogonDate)
select @frmbeg=  max(crimeID)-min(CrimeID)  from tblcrime 



SELECT count(o.crimeID)
from tblcrime o
inner join  
tblContractor ts 
on o.MainContractorID=ts.ContractorID

inner join 
tblBusiness tb 
on o.MainContractorBUID=tb.BusinessID
inner join tblservant tw on
o.servantID=tw.servantID

inner join tblUser u 
on  u.ContractorID=o.MainContractorID



where count(o.crimeID) between @lastLogonDate and @onemonthtime or count(o.crimeID) between @lastLogonDate and @oneweektime

END

But its giving an Error Like this "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". which part i want to modify....Plz help

1

1 Answers

1
votes

Any value that is determined by an aggregate on a query has to be put into HAVING as it is evaluated on the aggregated query, not on the source query. You also need to tell it what you want to group your counts by.

Try this as an example that assumes you want to find the MAINCONTRACTORID of the person who fits your criteria:

SELECT 
   count(o.crimeID),
   o.MainContractorID
from tblcrime o
inner join  
tblContractor ts 
on o.MainContractorID=ts.ContractorID

inner join 
tblBusiness tb 
on o.MainContractorBUID=tb.BusinessID
inner join tblservant tw on
o.servantID=tw.servantID

inner join tblUser u 
on  u.ContractorID=o.MainContractorID

GROUP BY 
   o.MainContractorID
HAVING 
   count(o.crimeID) between @lastLogonDate and @onemonthtime or count(o.crimeID) between @lastLogonDate and @oneweektime

NB: An aggregate is any value that is determined by a function on a set of results that will group, like COUNT, SUM, AVG..