gpt4 book ai didi

sql - 在INNER JOIN上返回一行

转载 作者:行者123 更新时间:2023-12-04 20:56:31 24 4
gpt4 key购买 nike

我只想从内部联接返回第一行。我有两个表:

TABLE_D和TABLE_E中的行可以具有相同的创建日期,因此我首先要从该集合中获取MAX(creationdate),然后是MAX(id)。这是我完整的查询:



SELECT
a.id as A_ID,
b.id as B_ID,
c.id as C_ID,
d.id as D_ID,
e.id as E_ID,
d.CREATIONDATE,
a.REFNUMBER,
a.DATECREATED,
a.INFO,
e.COST,
FROM
TABLE_A a
INNER JOIN TABLE_B b ON (b.id = a.id)
INNER JOIN TABLE_C c ON (c.id = b.id)
INNER JOIN TABLE_D d ON
(
c.i =
(
select
d.id
FROM TABLE_D
WHERE TABLE_D.id = c.id
AND TABLE_D.id =
(
select
max(id)
from TABLE_D t1
where c_id = c.id
and CREATIONDATE =
(
select
max(CREATIONDATE)
from TABLE_D t2
where t2.c_id = t1.c_id
)
)
)
)

INNER JOIN TABLE_E e ON
(
d.i =
(
select
e.d_id
from TABLE_E
where d_id = d.id
AND id =
(
select
max(id)
from e t1
where e.d_id = d.id
and CREATIONDATE =
(
select
max(CREATIONDATE)
from TABLE_E t2
where t2.d_id = t1.d_id
)
)
)
)






我的子查询获取具有最大creationdate的所有行,并且当我单独调用它时,从其最大id可以正常工作,但是当我将其添加到INNER JOIN(见上文)时,表D中的每个匹配行都得到一行我想要的是每个TABLE_A.id的一行,仅显示TABLE_D与TABLE_C关联的最新行以及TABLE_E与TABLE_D关联的最新行。

例如,目前我的结果集中的ID如下所示:



--------------------------------------------------------------------------
A_ID B_ID C_ID D_ID E_ID
--------------------------------------------------------------------------
1 101 201 301 401
1 101 201 301 402
1 101 201 301 403
1 101 201 302 404
1 101 201 302 405
1 101 201 302 406



我需要的是:


--------------------------------------------------------------------------
A_ID B_ID C_ID D_ID E_ID
--------------------------------------------------------------------------
1 101 201 302 406






在此先感谢您的帮助。

最佳答案

使用oracle11g中可用的解析函数ROW_NUMBER()

SELECT *
FROM
(
SELECT
a.id as A_ID,b.id as B_ID,c.id as C_ID,d.id as D_ID,e.id as E_ID,
d.CREATIONDATE,a.REFNUMBER,a.DATECREATED,a.INFO,e.COST,
row_number() over (
partition by a.id, b.id, c.id
order by d.CREATIONDATE DESC, d.id desc, e.CREATIONDATE DESC, e.id desc) RN
FROM TABLE_A a
INNER JOIN TABLE_B b ON (b.id = a.id)
INNER JOIN TABLE_C c ON (c.id = b.id)
INNER JOIN TABLE_D d ON d.c_id = c.id
INNER JOIN TABLE_E e ON e.d_id = d.id
) N
WHERE RN = 1


只要确保PARTITION和ORDER BY子句是正确的

partition by a.id, b.id, c.id
=> start numbering from 1 again when any one of these changes
order by d.CREATIONDATE DESC, d.id desc, e.CREATIONDATE DESC, e.id desc)
=> number the rows in this order

关于sql - 在INNER JOIN上返回一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4722362/

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