¿Cómo uso Count (*) en una declaración Where?
-
27-10-2019 - |
Pregunta
No entiendo por qué esto no funciona y cómo solucionarlo, probé varias cosas como escribir
select COUNT(p.OwnerUserId)
Pero eso no funciona y no entiendo los mensajes de error. No uso MS SQL (uso SQLite y MySQL).
¿Cómo escribo esta consulta para poder filtrar el QC por 10 o 50? (Donde QC> 50 y ...)
Básicamente, conecte el SQL a continuación en esta URL, ejecutela y verá 1 en los resultados.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
Solución
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
Otra opción es convertirlo en un subconsulto
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
Otros consejos
Debe usar la cláusula de tener para filtrar un campo agregado
Prueba esto:
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
Cuando esté utilizando agregados, debe usar having
en vez de where
.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow