ada*_*nne 7 sql oracle oracle11g
我想仅从内连接返回第一行.我有两张桌子:
TABLE_X | TABLE_Y
id | id creationdate xid
1 | 1 01/01/2011 1
2 | 2 01/01/2011 1
3 | 3 31/12/2010 2
4 | 4 28/12/2010 3
Run Code Online (Sandbox Code Playgroud)
表Y中的行可以具有相同的创建日期,因此我首先获得MAX(creationdate),然后从该集合获得MAX(id),例如:
SELECT a.id,
c.id,
d.id,
e.id,
d.CREATIONDATE,
a.REFNUMBER,
a.DATECREATED,
a.DESCRIPTION,
e.CATEGORYCODE,
e.OUTSTANDINGAM_MONAMT,
e.PREVPAIDAMOUN_MONAMT,
e.TOTALINCURRED_MONAMT,
e.LOSSFROMDATE,
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
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
当我自己调用它时,这可以工作,但是当我将它添加到INNER JOIN时,我为表Y中的每个匹配行获取一行.
我想要的是creationdate和id的最新记录,其中来自TABLE_X的xid = id.
“当我将它添加到内部联接时”?什么内连接?用什么内连接?这个问题严重不明确,但我认为你需要这个(我只使用视图来保持清晰,你可以轻松地将它们放在大括号中并构建一个大查询):
-- latest pairs of (id,creation) per xid
create view latest_id_per_xid as
select xid,max(id) id,max(creation) creation from table_y group by xid;
-- this view leaves only the rows from table_y that have the same (id,creation,idx)
-- as the newest rows identified in the former view (it's basically a semijoin)
-- you could also join on id alone
create view latest_whole_y as
select table_y.* from table_y natural join latest_id_per_xid;
-- now the answer is easy:
select * from table_x join latest_whole_y
Run Code Online (Sandbox Code Playgroud)
我手头没有数据库来检查小错误,但它应该运行良好。(警告:最大的假设是您永远不会有具有新 ID 和旧日期的记录)
| 归档时间: |
|
| 查看次数: |
12920 次 |
| 最近记录: |