我不明白为什么这不起作用以及如何解决它,我尝试了各种各样的事情,比如写
select COUNT(p.OwnerUserId)
但这不起作用,我不明白错误消息。我不使用MS SQL(我使用SQLite和MySQL)。
如何编写此查询以便我可以将QC过滤10或50? (其中QC> 50 AND ...)
基本上将下面的SQL插入到此URL中,运行它,您将在结果中看到1。 http://data.stackexchange.com/stackoverflow/query/new
SELECT
TOP 100
p.OwnerUserId AS [User Link],
sum(ViewCount) as VC,
avg(ViewCount) as AVC,
COUNT(p.OwnerUserId ) as QC
FROM Posts p
join Users on p.OwnerUserId = Users.Id
where PostTypeId = 1 and ViewCount<10000 and CommunityOwnedDate is null
group by p.OwnerUserId
order by AVC desc
答案 0 :(得分:7)
您需要使用Having子句来过滤聚合字段
试试这个:
SELECT
TOP 100
p.OwnerUserId AS [User Link],
sum(ViewCount) as VC,
avg(ViewCount) as AVC,
COUNT(p.OwnerUserId ) as QC
FROM Posts p
join Users on p.OwnerUserId = Users.Id
where PostTypeId = 1 and ViewCount<10000 and CommunityOwnedDate is null
group by p.OwnerUserId
HAVING COUNT(p.OwnerUserId ) > 50
order by AVC desc
答案 1 :(得分:2)
使用聚合时,应使用having
代替where
。
答案 2 :(得分:1)
SELECT
TOP 100
p.OwnerUserId AS [User Link],
sum(ViewCount) as VC,
avg(ViewCount) as AVC,
COUNT(p.OwnerUserId ) as QC
FROM Posts p
join Users on p.OwnerUserId = Users.Id
where PostTypeId = 1 and ViewCount<10000 and CommunityOwnedDate is null
group by p.OwnerUserId
HAVING COUNT(p.OwnerUserId ) between 10 and 50 -- <<<<<
order by AVC desc
另一种选择是使其成为子查询
SELECT
TOP 100
FROM (
SELECT
p.OwnerUserId AS [User Link],
sum(ViewCount) as VC,
avg(ViewCount) as AVC,
COUNT(p.OwnerUserId ) as QC
FROM Posts p
join Users on p.OwnerUserId = Users.Id
where PostTypeId = 1 and ViewCount<10000 and CommunityOwnedDate is null
group by p.OwnerUserId
) SQ
WHERE QC >= 50
order by AVC desc