2

我不明白为什么这不起作用以及如何解决它,我尝试了各种方法,例如写作

select COUNT(p.OwnerUserId)

但这不起作用,我不明白错误消息。我不使用 MS SQL(我使用 SQLite 和 MySQL)。

如何编写此查询,以便我可以按 10 或 50 过滤 QC?(其中 QC > 50 并且 ...)

基本上将下面的 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
4

3 回答 3

7

您需要使用 Have 子句来过滤聚合字段

试试这个:

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
于 2011-01-28T23:47:37.663 回答
3

当您使用聚合时,您应该使用having而不是where.

于 2011-01-28T23:47:27.357 回答
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
于 2011-01-28T23:48:05.653 回答