MySQL - 获取最低值

时间:2012-09-24 08:59:32

标签: mysql group-by

我的数据库结构包含列:id, name, value, dealer。我想检索每个 value的最低dealer行。我一直试图搞砸MIN()GROUP BY,仍然没有解决方案。

7 个答案:

答案 0 :(得分:17)

解决方法1:

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

溶液2:

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

这个问题很有名,所以在Mysql的手册中有一个特殊的页面。

选中此项: Rows Holding the Group-wise Maximum/Minimum of a Certain Column

答案 1 :(得分:4)

select id,name,MIN(value) as pkvalue,dealer from TABLENAME 
group by id,name,dealer;

在这里你按照ID,名称,经销商对所有行进行分组,然后你将得到最小值作为pkvalue。

答案 2 :(得分:2)

SELECT MIN(value),dealer FROM table_name GROUP BY dealer;

答案 3 :(得分:0)

请尝试以下操作:

SELECT dealer, MIN(value) as "Lowest value"
FROM value
GROUP BY dealer;

答案 4 :(得分:0)

首先,您需要为每个经销商解决最低价值,然后为特定经销商检索具有该值的行。我会这样做:

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 ) 

答案 5 :(得分:0)

select id, name, value, dealer from yourtable where dealer 
in(select min(dealer) from yourtable group by name, value)

答案 6 :(得分:0)

这些答案似乎错过了一个极端情况,即经销商有多个最小值,只想返回一行。

如果您只想为每个经销商分配一个值,则可以使用row_number分区-组-按经销商表,然后按值和ID排序数据。我们必须假设您想要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;

请注意,尽管该值,id和经销商已建立索引。如果不是这样,将进行全表扫描,并且会变得很慢...