简体   繁体   中英

How to fetch all rows with group by value in mysql?

I have a table say table1 which has 3 columns like id, name and age.

Records available in table1,

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.

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

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 .

If you are using mysql 8 or above you can use window functions.

select t1.*, count(t1.age) over (partition by t1.age) as same_age_count from table1 t1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM