Pergunta

I don't understand why this isn't working and how to fix it, I tried various things like writing

select COUNT(p.OwnerUserId)

but that doesn't work and I don't understand the error msgs. I don't use MS SQL (I use SQLite and MySQL).

How do i write this query so i can filter the QC by 10 or 50? (where QC > 50 AND ...)

Basically plug in the SQL below into this URL, run it and you'll see 1's in the results. 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
Foi útil?

Solução

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

Another option is to make it a subquery

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

Outras dicas

You need to use Having clause to filter an aggregated field

Try this:

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

When you are using aggregates, you should use having instead of where.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top