Click here to Skip to main content
15,897,291 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello everyone - i have a sql riddle that is driving me crazy.

I have 2 Tables
Item and itemposts

I want to joint them on item_no and then get the latest itempost, posting_id from the itempost table for each item.
Each posting_id has a created_date.

My hope will be to get a list containing the latest posting_id per item_no. Each item_no have several posting_id's connected but i only want the latest.
Posted
Comments
phil.o 3-Dec-15 11:47am    
Please improve your question with involved database tables structures, as well as the current query you have so far.

1 solution

(Not syntactically correct, but shows the point)

First step would be to do the following:

SQL
select item_no,  max(created_date) as 'created_date' from itemposts group by item_no


Now you have, for every item_no, the date for which you want the itempost record.

Once you have that, you can build a query around the first query (Using the first query as a subquery) to get what you want, more or less like this:

SQL
Select
  Item.item_no,
  itemposts.posting_id,
from
 item
  join itemposts on (item.item_no = itemposts.item_no)
  join (
    select 
        item_no,  
        max(created_date) as 'created_date' 
    from 
      itemposts 
    group by 
      item_no
  ) sq on 
      (sq.item_no = itemposts.item_no) and 
      (itemposts.created_date = sq.created_date)
 
Share this answer
 
v2
Comments
Kristian_dk 3-Dec-15 13:36pm    
That was exactly what i was looking for.. You have made my day! Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900