如何获取包含特定最小值的行?

时间:2017-07-31 12:17:10

标签: mysql sql

我有一个包含3行3列的表格。对于具有相同名称的所有行,我想检索位置列中具有最小值的行。在这个例子中。结果应该是(apple,red,3)和(melon,big,null)。

“position”列中的null值表示水果不在列表中。

name     category    position
apple     fruit        5
apple      red         3
melon      big       null

2 个答案:

答案 0 :(得分:4)

'data.frame': 50 obs. of 5 variables: $ Category : Factor w/ 10 levels "a","able","about",..: 5 8 6 3 8 8 8 2 3 4 ... $ Summ_Income :Class 'comma' int [1:50] 4397 3204 1788 4520 2643 2202 3317 5979 2332 9667 ... $ Summ_Securities:Class 'comma' int [1:50] 2263 9182 9100 2731 5791 5699 2443 5676 3020 3533 ... $ Summ_Bonds :Class 'comma' int [1:50] 2544 5690 7882 3599 4931 7025 1332 6046 9392 4912 ... $ Summ_Options :Class 'comma' int [1:50] 7237 1865 1332 4608 1103 6111 9505 4090 3200 5875 ... 让这很棘手。我不确定它是否应被视为“高”或“低”。让我假设“低”:

In [1]: import datetime

In [2]: wasNow = datetime.datetime.now()

In [3]: wasNow
Out[3]: datetime.datetime(2017, 7, 28, 14, 17, 21, 889530)

In [4]: wasNow.now()
Out[4]: datetime.datetime(2017, 7, 28, 14, 17, 30, 105077)

答案 1 :(得分:2)

SELECT 
    f.* 
FROM
(
    SELECT
        name, 
        MIN(IFNULL(position,0)) as min_position 
    FROM 
        fruits 
    GROUP BY 
        name
) tmp
LEFT JOIN 
    fruits f ON 
    f.name = tmp.name AND 
    IFNULL(f.position,0) = min_position
-- GROUP BY name 
-- optional if multiple (name, position) are possible for example
-- [apple,fruit,5], [apple,red,5]