仅返回基于多连接中的一列的最小记录
Posted
技术标签:
【中文标题】仅返回基于多连接中的一列的最小记录【英文标题】:Return only minimum record based on one column in a multiple join 【发布时间】:2021-10-06 22:36:57 【问题描述】:我有一个包含几个连接的查询,它返回两条记录,我只希望它为每个 acme_id(最小 acme_client_id)返回一条记录。 (或者最小的 acme_client.client_id,我不在乎。)我尝试了很多不同的方法,但我无法让它工作。
SELECT
acme_client_id,
acme_client.client_id,
acme_id
FROM
acme_client WITH (NOLOCK)
LEFT JOIN client WITH (NOLOCK) ON acme_client.client_id = client.client_id
LEFT JOIN acme_client_information WITH (NOLOCK) ON client.acme_client_information_id = acme_client_information.acme_client_information_id
WHERE
acme_client.acme_decisionmaker_ind = 1
and acme_client.acme_current_owner_ind = 0
AND (
acme_client.participant_start_date IS NULL
OR acme_client.participant_start_date < GETDATE()
)
AND (
acme_client.participant_end_date IS NULL
OR acme_client.participant_end_date > GETDATE()
)
AND (
acme_client.acme_client_id IN (
SELECT
acme_cooperating_entity_client.acme_client_id
FROM
acme_cooperating_entity_client WITH (NOLOCK)
)
)
)
【问题讨论】:
签出row_number()
停止使用nolock 溅出你的代码
提供样本数据和所需的输出
【参考方案1】:
可能是这样的
SELECT min(ac.acme_client_id) min_ac_id,
min(ac.client_id) min_c_id,
ac.acme_id
FROM acme_client ac
join acme_cooperating_entity_client acec on ac.acme_client_id=acec.acme_client_id
LEFT JOIN client c ON ac.client_id = c.client_id
LEFT JOIN acme_client_information aci ON c.acme_client_information_id = aci.acme_client_information_id
WHERE ac.acme_decisionmaker_ind = 1
and ac.acme_current_owner_ind = 0
AND (ac.participant_start_date IS NULL
OR ac.participant_start_date < GETDATE())
AND (ac.participant_end_date IS NULL
OR ac.participant_end_date > GETDATE())
group by ac.acme_id;
【讨论】:
以上是关于仅返回基于多连接中的一列的最小记录的主要内容,如果未能解决你的问题,请参考以下文章