[英]SQL Query: Iterate through rows with same values and count occurences
I have the following table structure:我有以下表结构:
Name Fruit
--------------------
Bob Apple
Bob Pear
Alice Apple
Alice Orange
Alice Orange
Bob Orange
Bob Apple
Alice Pear
Bob Orange
Bob Apple
I want to iterate through the Name column, and count the number of distinct Fruits.我想遍历 Name 列,并计算不同 Fruits 的数量。 The preferred output would be:首选输出将是:
Name Apple Pear Orange
----------------------------------
Bob 3 1 2
Alice 1 1 2
Does anyone know how I can write this as an SQL Query in MySQL workbench?有谁知道我如何在 MySQL 工作台中将其编写为 SQL 查询?
Use conditional aggregation:使用条件聚合:
select name,
sum(fruit = 'Apple') as num_apples,
sum(fruit = 'Pear') as num_pears,
sum(fruit = 'Orange') as num_oranges
from t
group by name;
You can use CASE Expression also您也可以使用 CASE 表达式
SELECT Name,
SUM(CASE WHEN fruit = 'Apple' THEN 1 ELSE 0 END) Apples,
SUM(CASE WHEN fruit = 'Pear' THEN 1 ELSE 0 END) Pear,
SUM(CASE WHEN fruit = 'Orange' THEN 1 ELSE 0 END) Orange
FROM Table1
GROUP BY Name;
Please, try with below SQL.请尝试使用以下 SQL。 "fruits" is name of table: “水果”是表的名称:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(IF(tf.Fruit = ''',
Fruit,
''', 1, 0)) AS ',
Fruit
)
) INTO @sql
FROM fruits;
SET @sql = CONCAT('SELECT tf.name, ',
@sql,
' FROM fruits tf
GROUP BY tf.name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.