[英]Returning row with max value on INNER JOIN
我不是 SQL 中最强大的,但我一直在管理..... 我的情况是我的一个 INNER JOINS 返回多行,我试图找到一种方法来获取具有最高值的行使用名为“确定性”的列。
该语句涉及两个表,dim_asset 和dim_asset_operating_system。 这些表由一个名为 asset_id 的公共字段和一个名为 os_description 的字段(在 dim_asset 上)和在 dim_asset_operating_system 上的 description 链接。
代码:
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;
但是,如果多条记录具有相同的最高确定性(平局),则此查询将仅返回其中一个,这在许多用例中并不是一种理想的行为。 如果您对所有记录感兴趣,只需使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.