Skip to content
Advertisement

Search by best values for every minute

The problem I’m having is that I have a table of data that has a new row added every second (imagine the structure {id, timestamp(datetime), value}). I would like to do a single query for MSSQL to go through the table and output only the number of objects that have the top 2 values asc for each minute ( also output ).

Any ideas please?

Sample data:

Advertisement

Answer

As mentioned by @ZoharPeled in the comments, you can use DATEDIFF and DATEADD to partition by minute. Then use DENSE_RANK to take the top two value results.

db<>fiddle

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