This question is very similar to : https://stackoverflow.com/posts/1503959/edit But I want to take it one step further, and create new columns for each age, with a count for that age.
I have a table of people:
name | age
--------
bill | 25
tom | 25
tom | 23
tom | 23
I want to query for all names, and additional columns that counts how many names are of the same age:
name | 23 | 25
----------------
bill | 0 | 1
tom | 2 | 1
What's the most efficient way of doing this? I fear that a sub-query will be slow, and I'm wondering if there's a better way . Is there?
In case you have many age values,dynamic pivot is very useful
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when age = ''',
age,
''' then 1 else 0 end) AS ','`',
age,'`'
) ORDER BY age
) INTO @sql
FROM
t;
SET @sql = CONCAT('SELECT name, ', @sql, '
FROM t
GROUP BY name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Easiest way how to do this in SQL is using GROUP BY
.
SELECT name, age, COUNT(*) AS occurence FROM table GROUP BY name, age
But you get data in different format. You need to reformat them in PHP, because SQL doesn't work way you want.
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.