在 INNER JOIN 上返回具有最大值的行

Returning row with max value on INNER JOIN

我不是 SQL 中最强的,但我一直在管理.....使用名为“确定性”的列获取具有最高值的行的方法。

该语句涉及两个表,dim_asset和dim_asset_operating_system。这些表由一个名为 asset_id 的公共字段和一个名为 dim_asset 的字段 os_description 以及 dim_asset_operating_system.

上的描述链接。

代码:

SELECT
    A.ip_address,
    A.os_type,
    A.os_vendor,
    A.os_family,
    A.os_name,
    A.os_version,
    A.os_description,
    A.os_system,
    B.certainty
FROM 
    dim_asset A
INNER JOIN 
    dim_asset_operating_system B ON A.asset_id = B.asset_id 
                                 AND A.os_description = B.description
WHERE 
    ip_address = '192.168.65.100';

输出:

   ip_address   | os_type | os_vendor | os_family | os_name | os_version |   os_description   |  os_system   | certainty
----------------+---------+-----------+-----------+---------+------------+--------------------+--------------+-----------
 192.168.65.100 |         | Ubuntu    | Linux     | Linux   | 16.04      | Ubuntu Linux 16.04 | Ubuntu Linux |         1
 192.168.65.100 |         | Ubuntu    | Linux     | Linux   | 16.04      | Ubuntu Linux 16.04 | Ubuntu Linux |         1
 192.168.65.100 |         | Ubuntu    | Linux     | Linux   | 16.04      | Ubuntu Linux 16.04 | Ubuntu Linux |      0.85
(3 rows)

理想情况下...我希望返回以下内容:

   ip_address   | os_type | os_vendor | os_family | os_name | os_version |   os_description   |  os_system   | certainty
----------------+---------+-----------+-----------+---------+------------+--------------------+--------------+-----------
 192.168.65.100 |         | Ubuntu    | Linux     | Linux   | 16.04      | Ubuntu Linux 16.04 | Ubuntu Linux |         1

在我上面的示例中,这只是一个记录...理想情况下,我需要将其扩展到数百万返回行的 10 位。

感谢您提供的任何帮助。

如果您希望获得最高的确定性,您只需要 ORDER BY 它并将结果集限制为 FETCH FIST ROW ONLY:

SELECT * FROM dim_asset A
INNER JOIN dim_asset_operating_system B ON A.asset_id = B.asset_id AND
                                           A.os_description = B.description
WHERE ip_address = '192.168.65.100'
ORDER BY certainty DESC
FETCH FIRST ROW ONLY;

但是,如果多个记录共享相同的最高确定性(并列),则此查询将 return 只是其中一个,这在许多用例中不是理想的行为。如果您对共享最高值的所有记录感兴趣,请使用 FETCH FIRST ROW WITH TIES在 PostgreSQL 13 中引入):

SELECT * FROM dim_asset A
INNER JOIN dim_asset_operating_system B ON A.asset_id = B.asset_id AND
                                           A.os_description = B.description
WHERE ip_address = '192.168.65.100'
ORDER BY certainty DESC
FETCH FIRST ROW WITH TIES;

演示:db<>fiddle