sql - Select unique barcode with max timestamp -
i'm trying write sql query using microsoft sql server.
my table looks similar 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 list of unique barcodes based on recent timestamps.
here not-working query i've been thinking of:
select distinct [barcode], [timestamp] [inventorylocatordb].[dbo].[inventory] max([timestamp])
edit i'd retain additional columns well. do bring together or someting.
for illustration want select the barcode latest timestamp , of other column info come e.g. products column
this should work:
select [barcode], max([timestamp]) [inventorylocatordb].[dbo].[inventory] grouping [barcode]
demo
edit
select [barcode], [products], [timestamp] [inventorylocatordb].[dbo].[inventory] [timestamp] = (select max([timestamp]) [inventorylocatordb].[dbo].[inventory] [barcode] = i.[barcode])
the query retains tuples same barcode
/ timestamp
. depending on granularity of timestamp
may not valid.
demo 2
there many ways "filter" above result.
e.g. 1 tuple per barcode
, latest timestamp
, greatest value of products
:
select [barcode], [products], [timestamp] [inventorylocatordb].[dbo].[inventory] [timestamp] = (select max([timestamp]) [inventorylocatordb].[dbo].[inventory] [barcode] = i.[barcode]) , [products] = (select max([products]) [inventorylocatordb].[dbo].[inventory] [barcode] = i.[barcode] , [timestamp] = i.[timestamp])
demo 3
sql sql-server
No comments:
Post a Comment