SQL Most recent record FROM second table by Id

0

I have two tables ( Opportunity and Stage ). I need to get for every Opportunity the table row Stage where StageTypeId is equal to input parameter .

Table Opportunity

  

Id, etc.

Table Stage

  

Id, CreatedOn, OpportunityId, StageTypeId.

Suppose I have opportunities "opportunity1" and "opportunity2" each with multiple Stages registered.

Passing StageTypeId I need to get the Opportunities that has this Id as the most recent one in the Stage table.

I'm trying the query below but is replicating the Stage that exists for a Opportunity to all other Opportunities .

It looks like you're ignoring this line: 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]

Thank you.

    
asked by anonymous 07.08.2018 / 19:31

1 answer

1

After some time I decided to execute the first query and then retrieve the data from the table Stage item by item in a Loop .

    
31.08.2018 / 15:12