小编典典

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

sql

我有下表。

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具有最低firmware_version

当我SELECT test_type, model, min(firmware_version) FORM temp_table GROUP BY test_type, model得到所需的内容后,一旦添加了avg_throughput列,就需要将其也添加到GROUP
BY子句,当我需要的只是每种类型avg_throughput的最低firmware_version要求时,它返回所有行model


阅读 177

收藏
2021-04-07

共1个答案

小编典典

在标准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;
2021-04-07