Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to get the comparative records from table in which I am recording the purchase details of different items. Let say an Item "ABC" which has a unique ID "111" purchased many time for a client now the question is it that how to retrieve the latest and previous record for this item for this specific client in sql query?

Example:
ItemCode Date Amount ClientID
111 01/01/2017 999 ABC
111 10/03/2017 1050 ABC
111 12/04/2017 1020 ABC

how to get

For ClientID=ABC
ItemCode Date Amount LastPurchase LastAmount
111 12/04/2017 1020 10/03/2017 1050

What I have tried:

Different queries but no luck. Tried different forums but did not found any result.
Posted
Updated 31-May-17 11:35am

1 solution

Something like this should work:
SQL
WITH cteSortedData As
(
    SELECT
        ItemCode,
        Date,
        Amount,
        ClientID,
        ROW_NUMBER() OVER (PARTITION BY ClientID, ItemCode ORDER BY Date DESC) As RN
    FROM
        YourTable
)
SELECT
    ItemCode,
    MAX(CASE RN WHEN 1 THEN Date ELSE Null END) As Date,
    MAX(CASE RN WHEN 1 THEN Amount ELSE Null END) As Amount,
    MAX(CASE RN WHEN 2 THEN Date ELSE Null END) As LastPurchase,
    MAX(CASE RN WHEN 2 THEN Amount ELSE Null END) As LastAmount,
    ClientID
FROM
    cteSortedData
WHERE
    RN In (1, 2)
GROUP BY
    ItemCode,
    ClientID
;
 
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