Question : SQL Subquery find previous record in a group

I would like some help with a subquery that I am trying to write, I have tried varies attempts and have not been able to figure it out.
A solution using SQL-99 syntax would be acceptable, although I am using Access to return the data.

Data sample:
TRAN_ID      DIST      ACT_COST      DATE
12345            19      100.00            12/31/2008
12345            20      100.00            1/31/2009
12345            21      100.00            1/31/2009    
12345            22      0                    1/31/2009    <- I want to return this record
12345            23      0                    2/28/2009
12345            24      0                    2/28/2009    <- and this record
12345            25      0                    3/31/2009
12345            26      0                    4/30/2009

Using the above data set I would like to write a query that will return the following
TRAN_ID     DIST      ACT_COST    DATE        PREV_DIST      PREV_ACT_COST      PREV_DATE
12345             24            0              2/28/2009        22            0                  1/31/2009

I have tried to write the subquery and I am lost, see the mess below.
SELECT DISTINCT
TRAN_ID,
MAX(DIST),
LAST(ACT_COST),
DATE
FROM TABLE A
WHERE DATE  = 2/28/2009
------   I NEED A SUBQUERY TO GET THE PREVIOUS RECORD USING THE GROUPING MAX(DIST) AND LAST(ACT_COST)
----------
GROUP BY TRAN_ID, DATE;

Answer : SQL Subquery find previous record in a group

The following code supports multiple TRAN_ID values. It still needs consecutive DIST values inside one TRAN_ID.

If you don't have consecutive values in DIST column you may either create another table with new autonumbered column and insert records from your table to this new table or you may simulate the Record number calculation using the DSum function (it could be another nightmare :-)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
SELECT orig.TRAN_ID, orig.DIST, orig.ACT_COST, orig.POST_DATE, chng.DIST_CHG, chng.ACT_COST_CHG, chng.POST_DATE_CHG
FROM (
  SELECT TABLE4.TRAN_ID AS TRAN_ID, Max(TABLE4.DIST) AS DIST, Last(TABLE4.ACT_COST) AS ACT_COST,
         TABLE4.POST_DATE AS POST_DATE 
    FROM TABLE4 
   GROUP BY TABLE4.TRAN_ID, TABLE4.POST_DATE 
  HAVING (((TABLE4.TRAN_ID)="12345") And ((TABLE4.POST_DATE)=#2/28/2009#)) 
   ORDER BY TABLE4.TRAN_ID, Max(TABLE4.DIST))  AS orig 
INNER JOIN (
  SELECT  lid.TRAN_ID, lid.DIST AS DIST_CHG, tbl.ACT_COST AS ACT_COST_CHG, tbl.POST_DATE AS POST_DATE_CHG
    FROM (
       SELECT t1.TRAN_ID, MAX(t1.DIST) AS DIST
         FROM Table4 AS t1 
        INNER JOIN Table4 AS t2 ON (t2.DIST=t1.DIST+1) AND (t2.TRAN_ID=t1.TRAN_ID)
        WHERE t1.ACT_COST<>t2.ACT_COST 
        GROUP BY t1.TRAN_ID) lid
    INNER JOIN Table4 tbl ON tbl.TRAN_ID = lid.TRAN_ID AND tbl.DIST = lid.DIST
          )  AS chng ON chng.TRAN_ID=orig.TRAN_ID ;
Random Solutions  
 
programming4us programming4us