Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select unique barcode with max timestamp

Tags:

sql

sql-server

I'm trying to write an SQL query using Microsoft SQL Server.

My table looks similar to this:

bardcode |  products |      timestamp

1234     |  12       | 2013-02-19 00:01:00
1234     |  17       | 2013-02-19 00:01:00
432      |  10       | 2013-02-19 00:01:00
432      |   3       | 2013-02-19 00:02:00
643      |  32       | 2013-02-19 00:03:00
643      |   3       | 2013-02-19 00:03:00
123      |  10       | 2013-02-19 00:04:00

I'm trying to get a list of unique barcodes based on the most recent timestamps.

Here is my not-working query I've been thinking of:

    SELECT DISTINCT [Barcode], [Timestamp]
    FROM [InventoryLocatorDB].[dbo].[Inventory]
    WHERE max([Timestamp]) 

EDIT I'd like to retain the additional columns as well. Do I do a join or someting.

For example I want to select the the barcode with the latest timestamp and would like all of the other column information to come with it e.g. products column

like image 814
visc Avatar asked Nov 24 '25 15:11

visc


1 Answers

This should work:

SELECT   [Barcode], max([TimeStamp])
FROM     [InventoryLocatorDB].[dbo].[Inventory]
GROUP BY [Barcode]

Demo

EDIT

SELECT [Barcode], [Products], [TimeStamp]
FROM   [InventoryLocatorDB].[dbo].[Inventory] AS I
WHERE  [TimeStamp] = (SELECT MAX([TimeStamp])
                      FROM   [InventoryLocatorDB].[dbo].[Inventory]
                      WHERE  [Barcode] = I.[Barcode])

The query retains tuples with the same BarCode / TimeStamp. Depending on the granularity of TimeStamp this may not be valid.

Demo 2

There are many ways to "filter" the above result.

E.g. only one tuple per BarCode, latest TimeStamp, greatest value of Products:

SELECT [Barcode], [Products], [TimeStamp]
FROM   [InventoryLocatorDB].[dbo].[Inventory] AS I
WHERE  [TimeStamp] = (SELECT MAX([TimeStamp])
                      FROM   [InventoryLocatorDB].[dbo].[Inventory]
                      WHERE  [Barcode] = I.[Barcode]) AND
       [Products]  = (SELECT MAX([Products])
                      FROM   [InventoryLocatorDB].[dbo].[Inventory]
                      WHERE  [Barcode] = I.[Barcode] and [TimeStamp] = I.[TimeStamp])

Demo 3

like image 76
manlio Avatar answered Nov 27 '25 17:11

manlio