If I have a table with columns id
, name
, score
, date
and I wanted to run a sql query to get the record where id = 2
with the earliest date in the data set.
Can you do this within the query or do you need to loop after the fact?
I want to get all of the fields of that record..
First, create an aggregate query that has two fields: GroupID and RecordDate. Group by the GroupID field, and choose the "Min" option for the RecordDate, to return the earliest date for each query.
SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE()); Example.
If you just want the date:
SELECT MIN(date) as EarliestDate FROM YourTable WHERE id = 2
If you want all of the information:
SELECT TOP 1 id, name, score, date FROM YourTable WHERE id = 2 ORDER BY Date
Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.
SELECT TOP 1 ID, Name, Score, [Date] FROM myTable WHERE ID = 2 Order BY [Date]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With