简体   繁体   中英

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 . 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

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.

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