Get The Latest values For Same ID/Duplicate ID

Posted on

Question :

enter image description here—————-I Want To Show Only Red marked product_id,on_hand,created_at, In this image Product_id have same Duplicate id but i want only last entry or latest product_id information and Show if last entry value is zero .

Answer :

Try this:

SELECT primary_table.product_id, primary_table.on_hand, primary_table.created_at 
     FROM 
`table_name` primary_table, 
(SELECT MAX(purchase_id) as pId FROM `table_name` Group by product_id) second_table 
     where primary_table.purchase_id = second_table.pId

Assuming your table is called purchases this would do what you want:

SELECT
    p.*
FROM
    (
      -- For every product_id, find maximum created_at time
      SELECT
          product_id, max(created_at) AS created_at
      FROM 
          purchases
      GROUP BY
          product_id
     ) AS mx 
     -- JOIN to the whole table
     JOIN purchases p ON
          mx.product_id = p.product_id AND mx.created_at = p.created_at
ORDER BY
     product_id ;

You have the mx subquery which relates a product_id with the latest (maximum) created_at value. You then JOIN this subquery to the original table to retrieve the whole row.

You can test a (smallish) version of it at SQLFiddle.

In Laravel Framework we can write on this,

Assume your table is “sellprices”

DB::select(
    DB::raw(
        "select sp1.* from (
            select product_id,max(updated_at) as last_date 
            from sellprices GROUP by product_id) as sp2 
         join sellprices sp1 
             on sp2.product_id = sp1.product_id 
             and sp2.last_date = sp1.updated_at 
         order by product_id"
    )
);

Try this:

SELECT product_id as pid, MAX(created_at) FROM `tableName` Group by product_id;

Leave a Reply

Your email address will not be published. Required fields are marked *