0
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

但是它给出了这样的错误“聚合可能不会出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中,并且正在聚合的列是外部引用”。我想修改哪一部分....请帮助

4

1 回答 1

1

任何由查询上的聚合确定的值都必须放入 HAVING 中,因为它是在聚合查询上评估的,而不是在源查询上。您还需要告诉它您想按什么分组计数。

试试这个例子,假设你想找到符合你标准的人的 MAINCONTRACTORID:

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

注意:聚合是由一组结果的函数确定的任何值,这些结果将分组,如 COUNT、SUM、AVG..

于 2012-04-26T06:17:00.453 回答