Skip to content
Advertisement

Last record per transaction

I am trying to select the last record per sales order.

My query is simple in SQL Server management.

SELECT *    
FROM DOCSTATUS

The problem is that this database has tens of thousands of records, as it tracks all SO steps.

ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

I would to see the most recent record per the SO

 ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate   
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

Advertisement

Answer

Well I’m not sure how that table has two Name columns, but one easy way to do this is with ROW_NUMBER():

;WITH cte AS 
(
  SELECT *, 
    rn = ROW_NUMBER() OVER (PARTITION BY SO ORDER BY Systemdate DESC)
  FROM dbo.DOCSTATUS
)
SELECT ID, SO, SL, Status, Reason, ..., Systemdate
FROM cte WHERE rn = 1;

Also please always reference the schema, even if today everything is under dbo.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement