[英]How do I COUNT rows of a GROUP BY query where a condition matches?
This is my persons table:这是我的人员表:
neighborhood birthyear
a 1958
a 1959
b 1970
c 1980
I'd like to get the COUNT
of people in an age group within every neighborhood.我想获得COUNT
社区中某个年龄组的人数。 For example, if I wanted to get everyone under the age of 18, I would get:例如,如果我想让所有人都未满 18 岁,我会得到:
neighborhood count
a 0
b 0
c 0
If I wanted to get everyone over 50, I'd get如果我想让每个人都超过 50 岁,我会得到
neighborhood count
a 2
b 0
c 0
I tried我试过了
SELECT neighborhood, COUNT(*)
FROM persons
WHERE YEAR(NOW()) - persons.birthyear < 18
GROUP BY neighborhood;
but this gives me 0 rows, when instead I want 3 rows with distinct neighborhoods and 0 count for each.但这给了我 0 行,而我想要 3 行具有不同邻域的行,每个行数为 0。 How would I accomplish this?我将如何做到这一点?
You can use conditional aggregation:您可以使用条件聚合:
SELECT neighborhood, SUM(YEAR(NOW()) - p.birthyear) as under_18,
SUM(YEAR(NOW()) - p.birthyear BETWEEN 34 AND 42) as age_34_42
FROM persons p
GROUP BY neighborhood;
I think that if the count is 0, the row doesn't appear.我认为如果计数为 0,则该行不会出现。 Your code seems correct to me, if you try it on the example with age 50, it should give you one row whith the expected line (neighborhood:a,count:2)你的代码对我来说似乎是正确的,如果你在 50 岁的例子上尝试它,它应该给你一行预期的行 (neighborhood:a,count:2)
I would recommend using a sub query:我建议使用子查询:
SELECT
count(*) [group-by-count-greater-than-ten]
FROM
(
SELECT
columnFoo,
count(*) cnt
FROM barTable
WHERE columnBaz = "barbaz"
GROUP BY columnFoo
)
AS subQuery
WHERE cnt > 10
In the above, the subquery
return result set is being used by the main query
as any other table.在上面, subquery
返回结果集被main query
用作任何其他表。
The column cnt
is no longer seen by the main query
as a computed field and does not have to reference the count()
function. main query
不再将列cnt
视为计算字段,并且不必引用count()
function。
However, inside the subquery
running a where
clause or a having
clause that must look at the alias cnt
column, the count()
function would have to be referenced as referencing cnt
in the subquery
would throw an error.但是,在运行必须查看别名cnt
列的where
子句或 have 子句的subquery
having
,必须引用count()
function,因为在subquery
中引用cnt
会引发错误。
In your case using a subquery
would look something like this.在您的情况下,使用subquery
看起来像这样。
SELECT
neighborhood,
age,
count(*) as cnt
FROM
(
SELECT
*,
(YEAR(NOW()) - birthyear) as age
FROM PERSONS
) as WithAge
WHERE age < 18
GROUP BY neighborhood, age
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.