根据另一列的最小值选择列

时间:2014-08-12 17:18:22

标签: sql postgresql greatest-n-per-group

我有下表。

test_type |  brand  | model  | band | firmware_version | avg_throughput
-----------+---------+--------+------+-----------------+----------------
 1client   | Linksys | N600   | 5ghz | 1               |          66.94
 1client   | Linksys | N600   | 5ghz | 2               |          94.98
 1client   | Linksys | N600   | 5ghz | 4               |         132.40
 1client   | Linksys | EA6500 | 5ghz | 1               |         216.46
 1client   | Linksys | EA6500 | 5ghz | 2               |         176.79
 1client   | Linksys | EA6500 | 5ghz | 4               |         191.44

我想选择avg_throughput最低的每个model的{​​{1}}。

当我firmware_version时,我得到了我想要的东西但是一旦我添加了SELECT test_type, model, min(firmware_version) FORM temp_table GROUP BY test_type, model列,它就要求我将它添加到GROUP BY子句中,这使得它在我需要的时候返回所有行每个avg_throughput类型的最低avg_throughput只是firmware_version

3 个答案:

答案 0 :(得分:3)

在标准SQL中,这可以使用窗口函数

来完成
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有distinct on运算符,它通常比具有窗口函数的相应解决方案更快:

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

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

答案 1 :(得分:1)

如果我正确地阅读你的帖子,这应该是你正在寻找的东西,我认为这是一种非常容易阅读的方式。 : - )

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

答案 2 :(得分:0)

我认为您需要SQL语句:

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)