如何在 where 语句中使用 Count(*)?
Posted
技术标签:
【中文标题】如何在 where 语句中使用 Count(*)?【英文标题】:How do i use Count(*) in a where statement? 【发布时间】:2011-06-17 13:45:18 【问题描述】:我不明白为什么这不起作用以及如何解决它,我尝试了各种方法,例如写作
select COUNT(p.OwnerUserId)
但这不起作用,我不明白错误消息。我不使用 MS SQL(我使用 SQLite 和 mysql)。
如何编写此查询,以便我可以按 10 或 50 过滤 QC? (其中 QC > 50 AND ...)
基本上将下面的 SQL 插入此 URL,运行它,您会在结果中看到 1。 https://data.stackexchange.com/***/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
【问题讨论】:
@Matt,这对我来说似乎是一个纯 sql 问题。内容与此相关,但问题只是询问 SQL 语法。 我不明白你想要什么。 【参考方案1】:您需要使用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
【讨论】:
将 WHERE 子句视为 FROM 的过滤器,将 HAVING 子句视为 GROUP BY(处理聚合的地方)的过滤器。【参考方案2】:当您使用聚合时,您应该使用having
而不是where
。
【讨论】:
我一生中从未见过(因此从未使用过)“拥有” @Acidzombie24:HAVING 是一个很棒的工具。使用它,你会爱上它!【参考方案3】: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
【讨论】:
以上是关于如何在 where 语句中使用 Count(*)?的主要内容,如果未能解决你的问题,请参考以下文章
mysql语句的简化:from中的临时表作为where中的条件
为啥sql查询语句中的count(*)等聚合函数可以放在having后面,而不能放在where后面?
如何在 Doctrine 查询生成器中进行多个 WHERE IN 列查询?