SQL Query用于获取多个最小值

时间:2015-07-02 10:56:41

标签: mysql sql

输入

+----+----+----+
| in | tn | 20 |
+----+----+----+
| in | ka | 18 |
+----+----+----+
| in | ap | 30 |
+----+----+----+
| us | la | 12 |
+----+----+----+
| us | ca | 20 |
+----+----+----+
| us | ny | 5  |
+----+----+----+

期望输出

+----+----+----+
| in | ka | 18 |
+----+----+----+
| us | ny | 5  |
+----+----+----+

如上面的输出所示,我需要每个国家及其价值最低的州。

select a.country, a.state, a.value
from table1 a
where a.value in (select min(value) from table1);

使用上面的查询,我将根据整个表的最小值获取输出。

+----+----+---+
| us | ny | 5 |
+----+----+---+

我需要每个国家及其各自州的最低价值。

6 个答案:

答案 0 :(得分:2)

使用您的方法,您需要一个相关的子查询:

select a.country, a.state, a.value
from table1 a
where a.value in (select min(value)
                  from table1 b
                  where a.country = b.country);

答案 1 :(得分:1)

您也可以尝试 -

SELECT b.* 
FROM mytable b 
JOIN (SELECT country,MIN(val) AS val FROM mytable GROUP BY country) AS a ON b.val=a.val AND a.country=b.country

答案 2 :(得分:0)

select country,min(value) from table1 group by country

答案 3 :(得分:0)

许多方法可以做到这一点,例如:

SELECT a.country,
  ( SELECT b.state
    FROM table1 b
    WHERE b.country = a.country AND b.value = MIN(a.value)) state,
  MIN(a.value)
FROM table1 a
GROUP BY a.country

答案 4 :(得分:0)

尝试以下,

您可以对此查询使用排名功能。

Select country, state, value from  
(
    Select row_number() over (order by country, value) as row_id ,
    country, state, value
)T
where row_id == 1

答案 5 :(得分:0)

无需子查询或加入!很简单:

+----+----+----+
| in | ka | 18 |
+----+----+----+
| us | ny | 5  |
+----+----+----+

输出:

{{1}}