I need help with a MySQL query to count the number of times a combination of the same age_from and age_to occur.
Sample data:
age_from age_to
+---------+-------+
18 | 100
30 | 75
18 | 50
18 | 100
30 | 75
18 | 50
30 | 75
+---------+------+
Desired result:
18 to 100 = 2
30 to 75 = 3
18 to 50 = 2
I have already tried this:
SELECT
`p_age_from` AS `age_from`,
`p_age_to` AS `age_to`,
COUNT(`p_age_from`) AS `user_count`
FROM `user`
GROUP BY `p_age_from`, `p_age_to`
ORDER BY `p_age_from`
You can use CONCAT to join the age_from and age_to values. Then use this to group and count the data:
SELECT
CONCAT(`age_from`,' to ',`age_to`) as 'grouping',
COUNT('grouping') AS `user_count`
FROM `user`
GROUP BY grouping
You can get your result using following query
SELECT CONCAT(age_from,' to ',age_to,' = ',count(age_to)) as 'age_from to age_to' FROM user GROUP BY age_from, age_to ORDER BY age_from;
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.