gpt4 book ai didi

sql - 只需要从 INNER JOIN 返回一行

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

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

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

表 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
)
)
)
)

这在我自己调用它时有效,但是当我将它添加到 INNER JOIN 时,我为表 Y 中的每个匹配行获取一行。

我想要的是来自 TABLE_X 的创建日期和 id 的最新记录,其中 xid = id。

最佳答案

试试这个查询

select *,(
select top 1 creationdate from Table_Y
where from Table_Y.xId = m.id
order by Table_Y.CreationDate
)
from Table_X m

子查询将选择具有最大创建日期的前 1 个结果,主查询将选择所有记录,以便您获得所需的结果

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

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