[英]SELECT query that displays the name of each record once and the count of instances
Is it possible to write a SELECT query that displays the name of each record once and the count of how many instances of that record there are for certain criteria? 是否可以编写一个SELECT查询,该查询显示每个记录的名称一次,以及该记录有多少个实例的数量?
For example, If I have a table with the following records: 例如,如果我有一个包含以下记录的表:
How can I get the SELECT query to display the following: 如何获取SELECT查询以显示以下内容:
You can use conditional aggregation: 您可以使用条件聚合:
select customer,
sum( status = 'Disposed' ) as num_disposed,
sum( status = 'Transported' ) as num_transported
from t
group by customer;
MySQL treats boolean expressions like integers in a numeric context, with 0 for false and 1 for true. MySQL将布尔表达式视为数字上下文中的整数,0表示false,1表示true。 So, just adding up the boolean is a simple way to count the number of rows that match the condition. 因此,只需将布尔值相加就可以计算出与条件匹配的行数。
you can use a group by on case ansum for case 你可以使用一个案例ansum案例组
select customer, sum(case when status ='disposed' then 1 else 0 end) count_disposed
sum(case when status ='trasposed' then 1 else 0 end) count_trasposed
from my_table
group by customer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.