我有下表。
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
。
答案 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)