Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table "ProductStatusHistory" witch contain the history of a Product request.

ID   ID_Product   ID_Request   Status            Category   ID_Lab   Created_ON
1     40           5         Clinic Requested   Cat1       2       02-09-2015 08:00:00
2     40           5         Lab Request        Cat1       2       03-09-2015 08:00:00
3     40           5         Started            Cat1       2       04-09-2015 08:00:00
4     40           5         Completed          Cat1       2       05-09-2015 08:00:00
5     41           5         Clinic Request     Cat1       2       02-09-2015 08:00:00
6     41           5         Lab Request        Cat1       2       03-09-2015 09:00:00
7     41           5         Started            Cat1       2       04-09-2015 09:00:00
8     41           5         Cancelled          Cat1       2       05-09-2015 09:00:00


I need to select the product for each request (a Request (ID_Request) can have 1 or more product request (ID_Product)) with the last status associated. The output that I need it should be like this:
ID_Request    ID_Product    Status       Category     ID_Lab      Created_ON   
5               40          Completed      Cat1         2       05-09-2015 08:00:00
5               41          Cancelled      Cat1         2       05-09-2015 09:00:00


I have tried this query:

SQL
select   IDProduct 
      ,  SelectedProd
      ,  Category
      ,  CreatedOn
      ,  Status
from ProductStatusHistory
where ID_Req=5 and CreatedOn=(select  max(CreatedOn) from ProductStatusHistory) 


But it gives me always the last row in the table for the indicated request ID.

ANY SOLUTION PLEASE ?
Posted

SELECT P.ID , P.ID_Product , P.ID_Request , P.Status , P.Category, P.ID_Lab , P.Created_ON
FROM PRODUCT P
INNER JOIN (
select ID_Request, ID_Product, max(id) ID
from product WHERE ID_Request = 5 group by ID_Request, ID_Product

) T on T.ID = P.ID
 
Share this answer
 
v2
Comments
Leila Toumi 1-Oct-15 7:17am    
Thanks a lot Gauri Chodanker it works successfully :)
Hi,

The Best Approach to achieve this is create one more column like SNo, and for new status you can increment the Sno against product and while fetching time get result with max SNo.
 
Share this answer
 

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