[英]How to fetch all rows with group by value in mysql?
Records available in table1,表1中可用的记录,
id name age ------------------- 1 xxx 12 2 yyy 21 3 zzz 12 4 aaa 19 5 ccc 21 6 fff 12
I need result like this,我需要这样的结果,
id name age same_age_count ----------------------------------- 1 xxx 12 3 2 yyy 21 2 3 zzz 12 3 4 aaa 19 1 5 ccc 21 2 6 fff 12 3
This is what my expected result.
Note: same_age_count is the count value of repeated age in the table.注: same_age_count 为表中重复年龄的计数值。
I have tried this query,我试过这个查询,
select *, count(age) as same_age_count from table1 group by(age); id name age same_age_count ----------------------------------- 1 xxx 12 3 2 yyy 21 2 3 aaa 19 1
but it returns 3 records only, please give me a query for my expected result..但它只返回 3 条记录,请查询我的预期结果。
Thank you.谢谢你。
Try this:尝试这个:
SELECT T1.*,T2.same_age_count
FROM TableName T1
JOIN
(SELECT age,Count(age) as same_age_count
FROM TableName
GROUP BY age) T2
ON T1.age=T2.age
Result:结果:
ID NAME AGE SAME_AGE_COUNT
1 xxx 12 3
2 yyy 21 2
3 zzz 12 3
4 aaa 19 1
5 ccc 21 2
6 fff 12 3
See result in SQL Fiddle .在SQL Fiddle 中查看结果。
If you are using mysql 8 or above you can use window functions.如果您使用的是 mysql 8 或更高版本,则可以使用窗口函数。
select t1.*, count(t1.age) over (partition by t1.age) as same_age_count from table1 t1; select t1.*, count(t1.age) over (partition by t1.age) as same_age_count from table1 t1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.