通过ID从第二个表开始的SQL最新寄存器

时间:2018-08-07 17:25:28

标签: sql oracle subquery

我有2个表(机会和阶段)。我需要通过StageTypeId获得每个阶段的最新机会。

机会:ID等 阶段:Id,CreatedOn,OpportunityId,StageTypeId。

让我们假设我分别拥有“ opportunity1”和“ opportunity2”,并添加了许多阶段。

通过传递StageTypeId,我需要获得具有此StageTypeId最新的机会。

我正在尝试以下查询,但它为所有机会复制了同一阶段。

似乎忽略了这一行:“ AND {Stage}。[OpportunityId] = ID”

SELECT {Opportunity}.[Id] ID,
       {Opportunity}.[Name],
       {Opportunity}.[PotentialAmount],
       {Contact}.[FirstName], 
       {Contact}.[LastName],
       (SELECT * FROM 
            (
                SELECT {Stage}.[StageTypeId]
                  FROM {Stage}         
                 WHERE {Stage}.[StageTypeId] = @StageTypeId  
                   AND {Stage}.[OpportunityId] = ID       
                 ORDER BY {Stage}.[CreatedOn] DESC
            ) 
        WHERE ROWNUM = 1) AS StageTypeId     
 FROM {Opportunity}
 LEFT JOIN {Contact} 
   ON {Opportunity}.[ContactId] = {Contact}.[Id]

谢谢

2 个答案:

答案 0 :(得分:0)

大多数DBMS支持fetch first子句因此,您可以执行以下操作:

select o.*
from Opportunity o
where o.StageTypeId = (select s.StageTypeId 
                       from Stage s
                       where s.OpportunityId = o.id
                       order by s.CreatedOn desc
                       fetch first 1 rows only
                      );

答案 1 :(得分:0)

您可以尝试以下所有dbms支持的方式

   select TT*. ,o*. from
   (
   select s1.OpportunityId,t.StageTypeId from Stage s1 inner join

    (select StageTypeId,max(CreatedOn) as createdate Stage s
    group by StageTypeId
    ) t
    on s1.StageTypeId=t.StageTypeId and s1.CreatedOn=t.createdate 
   ) as TT inner join Opportunity o on TT.OpportunityId=o.id