gpt4 book ai didi

SQL - 另一个选择语句的 Where 子句?

转载 作者:行者123 更新时间:2023-12-04 06:51:08 24 4
gpt4 key购买 nike

我有以下查询:

select r.people_code_id [People Code ID], r.resident_commuter [Campus6],
c1.udormcom [AG], aR.RESIDENT_COMMUTER [AG Bridge], ar.ACADEMIC_SESSION,
ar.ACADEMIC_TERM, ar.academic_year, ar.revision_date
from RESIDENCY r
left join AG_Common..CONTACT1 c1 on r.PEOPLE_CODE_ID=c1.key4
left join AG_Common..CONTACT2 c2 on c1.ACCOUNTNO=c2.accountno
left join AGPCBridge..ArchiveRESIDENCY aR on r.PEOPLE_CODE_ID=aR.PEOPLE_CODE_ID
where r.ACADEMIC_YEAR='2010'
and r.ACADEMIC_TERM='Fall'
and SUBSTRING(c1.udormcom,1,1)<>r.resident_commuter
and r.ACADEMIC_SESSION='Und 01'
and aR.ACADEMIC_SESSION='Und 01'
and aR.ACADEMIC_TERM='Fall'
and aR.ACADEMIC_YEAR='2010'
and SUBSTRING(c1.udormcom,1,1)=aR.RESIDENT_COMMUTER

我需要在 where 段中添加另一个子句。我有这个查询:
 select DISTINCT * from RESIDENCY where ACADEMIC_YEAR='2010' and
ACADEMIC_TERM='Fall' and ACADEMIC_SESSION='Und 01' ORDER BY revision_date DESC

这仅获取每个人的最新行。我想做类似(伪代码)的事情:
WHERE r.people_code_id and r.revision_date are in (select DISTINCT * from
RESIDENCY where ACADEMIC_YEAR='2010' and ACADEMIC_TERM='Fall' and
ACADEMIC_SESSION='Und 01' ORDER BY revision_date DESC)

我在 SQL 2000 兼容模式下运行(尽管它实际上运行的是 SQL 2008)。

最佳答案

我根据您要添加的内容重新编写了您的查询:

WITH residency_cte AS (
SELECT TOP (1)
r.people_code_id,
r.resident_commuter,
r.academic_year,
r.academic_term,
r.academic_session
FROM RESIDENCY r
WHERE r.academic_year = '2010'
AND r.academic_term = 'Fall'
AND r.academic_session = 'Und 01'
ORDER BY revision_date DESC)
SELECT r.people_code_id,
r.resident_commuter [Campus6],
c1.udormcom [AG],
aR.RESIDENT_COMMUTER,
ar.ACADEMIC_SESSION,
ar.ACADEMIC_TERM,
ar.academic_year,
ar.revision_date
FROM residency_cte r
LEFT JOIN AG_Common..CONTACT1 c1 ON c1.key4 = r.PEOPLE_CODE_ID
AND SUBSTRING(c1.udormcom, 1, 1) != r.resident_commuter
LEFT JOIN AG_Common..CONTACT2 c2 ON c2.accountno = c1.ACCOUNTNO
LEFT JOIN AGPCBridge..ArchiveRESIDENCY aR ON aR.PEOPLE_CODE_ID = r.PEOPLE_CODE_ID
AND aR.ACADEMIC_SESSION = r.academic_session
AND aR.ACADEMIC_TERM = r.academic_term
AND aR.ACADEMIC_YEAR = r.academic_year
AND SUBSTRING(c1.udormcom, 1, 1) = aR.RESIDENT_COMMUTER

唯一的问题是 udormcom列位置 - 一旦我知道它来自哪个表,我就会将该子句向上移动到连接中。我还更新了对 ArchiveRESIDENCY 的连接。表,因此您只需在一处调整日期。

但请注意,使用子字符串匹配另一列永远不会表现良好 - 除非数据模型更改以纠正该问题,否则永远不会真正优化。

关于SQL - 另一个选择语句的 Where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3118656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com