开发者

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 resu开发者_Python百科lts. 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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜