【问题标题】:SELECT query that displays the name of each record once and the count of instancesSELECT 查询显示每条记录的名称一次和实例数
【发布时间】:2019-05-20 03:46:42
【问题描述】:

是否可以编写一个 SELECT 查询,显示每条记录的名称一次,以及该记录有多少个符合某些条件的实例的计数?

例如,如果我有一个包含以下记录的表:

如何让 SELECT 查询显示以下内容:

【问题讨论】:

  • 做一个GROUP BY。使用case表达式进行条件聚合!
  • 你能给我举个例子吗?
  • 平心而论,如果不可能的话,sql的用处会很有限

标签: mysql sql select


【解决方案1】:

您可以使用条件聚合:

select customer,
       sum( status = 'Disposed' ) as num_disposed,
       sum( status = 'Transported' ) as num_transported
from t
group by customer;

MySQL 将布尔表达式视为数字上下文中的整数,0 表示假,1 表示真。因此,将布尔值相加是一种计算符合条件的行数的简单方法。

【讨论】:

    【解决方案2】:

    您可以在 case ansum 上使用 group by

     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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 2011-12-06
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多