selecting a column based on a minimum value of another column

北城余情 提交于 2019-12-01 08:56:42

In standard SQL this can be done using a window function

select test_type, model, firmware_version, avg_throughput
from (
  select test_type, model, firmware_version, avg_throughput, 
         min(firmware_version) over (partition by test_type, model) as min_firmware
  from temp_table
) t
where firmware_version = min_firmware;

Postgres however has the distinct on operator which is usually faster than the corresponding solution with a window function:

select distinct on (test_type, model) 
       test_type, model, firmware_version, avg_throughput
from temp_table
order by test_type, model, firmware_version;

SQLFiddle example: http://sqlfiddle.com/#!15/563bd/1

This should be what you're looking for if I'm reading your post correctly, and I think it's a pretty easily readable way of doing it. :-)

WITH min_firmware_version (model, firmware_version)
AS
(
    SELECT
        model,
        MIN(firmware_version)
    FROM temp_table
    GROUP BY
        model
)
SELECT
    temp_table.model,
    temp_table.firmware_version,
    temp_table.avg_throughput
FROM temp_table
INNER JOIN min_firmware_version
    ON temp_table.model = min_firmware_version.model
    AND temp_table.firmware_version = min_firmware_version.firmware_version

I think you need that SQL statement:

SELECT t.test_type, t.model, t.firmware_version, t.avg_throughput 
FROM temp_table t 
WHERE t.firmware_version = (SELECT min(firmware_version) FROM temp_table) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!