简体   繁体   English

使用 DISTINCT 在 INNER JOIN 中获取唯一的 SQL 列

[英]Using DISTINCT to get a unique SQL column in an INNER JOIN

Hello I am trying to run the following query to select one of each host_id, but filter out the other rows if the host_id is the same.您好,我正在尝试运行以下查询来选择每个 host_id 之一,但如果 host_id 相同,则过滤掉其他行。 However, even when using distinct, I get all of the rows.但是,即使使用不同的,我也得到了所有的行。 Can someone help me understand why that is?有人可以帮我理解为什么会这样吗? How would I be able to change this so that only the host_id is unique?我如何才能改变这一点,以便只有 host_id 是唯一的? Thank you.谢谢你。

SELECT DISTINCT host_id hostid, host.description customer_name, data_template_data.data_source_path file, host.hostname host_name
FROM data_local
JOIN data_template_data ON data_local.id = data_template_data.local_data_id
LEFT JOIN host ON data_local.host_id = host.id
WHERE data_template_data.data_template_id = 41
AND host.disabled=''
AND data_template_data.data_source_path IS NOT NULL

You need aggregation or window functions.您需要聚合或窗口函数。 Possibly the simplest method is:可能最简单的方法是:

with h as (
      <your query here>
     )
select h.*
from (select h.*,
             row_number() over (partition by host_id order by host(id) as seqnum
      from h
     ) h
where seqnum = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM