我想仅从内连接返回第一行。我有两张桌子:
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
)
)
)
)
我的子查询获取具有最大创建日期的所有行,并且当我自己调用它时,max id工作正常但是当我将它添加到INNER JOIN(参见上文)时,我为每个匹配的行获取一行在表D和表E中。我想要的是每个TABLE_A.id一行,仅显示与TABLE_C关联的TABLE_D中的最新行以及与TABLE_D关联的TABLE_E中的最新行。
例如,我的结果集中的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
提前感谢您的帮助。
答案 0 :(得分:1)
使用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
答案 1 :(得分:1)
我要做的是将内部查询移动到select子句。我将在过滤时保持直接映射
SELECT
a.id as A_ID,
b.id as B_ID,
c.id as C_ID,
(select max(d.id) from d where d.id =c.id) as d_id)
FROM
TABLE_A a
INNER JOIN TABLE_B b ON (b.id = a.id)
INNER JOIN TABLE_C c ON (c.id = b.id)
答案 2 :(得分:0)
您可以在子查询中插入查询并使用WHERE ROWNUM< 2过滤器。
SELECT * FROM
(/* Your SQL */)
WHERE ROWNUM < 2
答案 3 :(得分:-1)
这可能对你有用吗?
SELECT TOP 1 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 = d.id) INNER JOIN TABLE_E e ON ( d.i = e.id ) ORDER BY d.creationdate DESC, e.creationdate DESC