使用COUNT()选择查询

时间:2014-03-28 20:10:05

标签: sql sql-server sql-server-2008

在此查询中有一个错误:

"Column 'upload_news.upload_time' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause."

我想显示两个日期之间与国家/地区名称相关的不同国家/地区的记录数量;

select count(Distinct news_id) AS TotalRecords, country 
from upload_news 
group by country 
having [upload_time] between GetDate()-2 AND GetDate()

2 个答案:

答案 0 :(得分:1)

所有数据分组后,HAVING子句将运行,因此您只能过滤分组数据的聚合。

如果要在数据分组之前过滤行,则需要使用WHERE子句:

select count(Distinct news_id) AS TotalRecords, country 
from upload_news 
where [upload_time] between GetDate()-2 AND GetDate()
group by country 

注意,WHERE子句需要在 GROUP BY子句之前

答案 1 :(得分:0)

此查询:

select count(Distinct news_id) AS TotalRecords, country 
 from upload_news 
group by country 
having [upload_time] between GetDate()-2 AND GetDate()

应该是:

 select count(Distinct news_id) AS TotalRecords, country 
 from upload_news 
 where upload_time between (NOW()- INTERVAL 2 DAY) AND NOW()
 group by country