Search code examples
sql-servert-sqldataexplorer

How do i use Count(*) in a where statement?


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. 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

Solution

  • 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