简体   繁体   English

计算至少一组MySQL的行数

[英]Count number of rows that are at the minimum of a group MySQL

I have a table that contains all the distinct names from another table, and then a column that holds the minimum value that the name received. 我有一个表,其中包含另一个表中所有不同的名称,然后是一列,其中包含该名称收到的最小值。 For example, the table looks like this: 例如,该表如下所示:

table1
Name | min_value
a    | 1
b    | 2
c    | 4

The original table looks like this: 原始表如下所示:

table2
Name | value
a    | 1
b    | 2
c    | 4
a    | 2
c    | 8
a    | 1

I want to return the number of times that the minimum value occurs within the original table. 我想返回最小值在原始表中出现的次数。 So, in this example it would return something like this: 因此,在此示例中,它将返回如下内容:

output_table
Name | times_at_min
a    | 2
b    | 1
c    | 1

Any help would be appreciated, thanks in advance. 任何帮助将不胜感激,在此先感谢。

One way to do it is: 一种方法是:

SELECT m.Name,
       min_value,
       COUNT(CASE WHEN m.value = min_value THEN 1 END) As times_at_min
FROM mytable AS m
INNER JOIN (
   SELECT Name, 
          MIN(value) AS min_value       
   FROM mytable
   GROUP BY Name ) AS g
ON m.Name = g.Name
GROUP BY Name   

In a subquery you select MIN(value) per Name . 在子查询中,每个Name选择MIN(value) Joining with the derived table of this subquery, you can perform conditional aggregation so as to calculate the number of times the minimum value appears in the original table. 通过与该子查询的派生表连接,您可以执行条件聚合 ,以计算最小值在原始表中出现的次数。

Fiddle demo here 小提琴演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM