【问题标题】:How do i use Count(*) in a where statement?如何在 where 语句中使用 Count(*)?
【发布时间】: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/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

【问题讨论】:

  • @Matt,这对我来说似乎是一个纯 sql 问题。内容与此相关,但问题只是询问 SQL 语法。
  • 我不明白你想要什么。

标签: sql-server tsql dataexplorer


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 2010-09-23
    • 2015-09-02
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    相关资源
    最近更新 更多