MySQL - Fetching lowest value

后端 未结 7 1240
醉酒成梦
醉酒成梦 2020-12-06 03:14

My database structure contains columns: id, name, value, dealer. I want to retrieve row with lowest value for each dealer

相关标签:
7条回答
  • 2020-12-06 03:22

    These answers seem to miss the edge case of having multiple minimum values for a dealer and only wanting to return one row.

    If you want to only want one value for each dealer you can use row_number partition - group - the table by dealer then order the data by value and id. we have to make the assumption that you will want the row with the smallest id.

    SELECT ord_tbl.id, 
           ord_tbl.name, 
           ord_tbl.value, 
           ord_tbl.dealer
    FROM (SELECT your_table.*, 
          ROW_NUMBER() over (PARTITION BY dealer ORDER BY value ASC, ID ASC) 
          FROM your_table 
         ) AS ord_tbl
    WHERE ord_tbl.ROW_NUMBER = 1;
    

    Be careful though that value, id and dealer are indexed. If not this will do a full table scan and can get pretty slow...

    0 讨论(0)
  • 2020-12-06 03:23
    select id,name,MIN(value) as pkvalue,dealer from TABLENAME 
    group by id,name,dealer;
    

    here you group all rows by id,name,dealer and then you will get min value as pkvalue.

    0 讨论(0)
  • 2020-12-06 03:26

    First you need to resolve the lowest value for each dealer, and then retrieve rows having that value for a particular dealer. I would do this that way:

    SELECT a.*
    FROM   your_table AS a
           JOIN (SELECT dealer,
                        Min(value) AS m
                 FROM   your_table
                 GROUP  BY dealer) AS b
             ON ( a.dealer= b.dealer
                  AND a.value = b.m ) 
    
    0 讨论(0)
  • 2020-12-06 03:28

    Try following:

    SELECT dealer, MIN(value) as "Lowest value"
    FROM value
    GROUP BY dealer;
    
    0 讨论(0)
  • 2020-12-06 03:40

    Solution1:

    SELECT t1.* FROM your_table t1
    JOIN (
      SELECT MIN(value) AS min_value, dealer
      FROM your_table 
      GROUP BY dealer
    ) AS t2 ON t1.dealer = t2.dealer AND t1.value = t2.min_value
    

    Solution2:

    SELECT t1.* FROM your_table t1
    LEFT JOIN your_table t2
    ON t1.dealer = t2.dealer AND t1.value > t2.value
    WHERE t2.value IS NULL
    

    This problem is very famous, so there is a special page for this in Mysql's manual.

    Check this: Rows Holding the Group-wise Maximum/Minimum of a Certain Column

    0 讨论(0)
  • 2020-12-06 03:40
    select id, name, value, dealer from yourtable where dealer 
    in(select min(dealer) from yourtable group by name, value)
    
    0 讨论(0)
提交回复
热议问题