Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query Grabs Earliest Entry Per Other Value

Tags:

c#

linq

Let's say I have a database that has a bunch of stock quotes

TableQuotes
2010-07-22 09:45:00.000, "ABC", 102.23
2010-07-22 09:45:00.000, "EFG", 24.65
2010-07-22 09:45:00.000, "HIJ", 14.20
2010-07-22 10:45:00.000, "ABC", 104.25
2010-07-22 10:45:00.000, "EFG", 26.09
2010-07-22 10:45:00.000, "HIJ", 12.43
2010-07-23 09:45:00.000, "ABC", 101.23
2010-07-23 09:45:00.000, "EFG", 23.65
2010-07-23 09:45:00.000, "HIJ", 16.20
2010-07-23 10:45:00.000, "ABC", 99.26
2010-07-23 10:45:00.000, "EFG", 22.09
2010-07-23 10:45:00.000, "HIJ", 11.43
...

I want to know how to write a query that:
1. Grabs only one stock quote per symbol per day
2. Grabs the earliest stock quote of each day for each symbol

so for instance, the desired result from my example table would be:

Result
2010-07-22 09:45:00.000, "ABC", 102.23
2010-07-22 09:45:00.000, "EFG", 24.65
2010-07-22 09:45:00.000, "HIJ", 14.20
2010-07-23 09:45:00.000, "ABC", 101.23
2010-07-23 09:45:00.000, "EFG", 23.65
2010-07-23 09:45:00.000, "HIJ", 16.20
like image 429
sooprise Avatar asked Feb 26 '23 14:02

sooprise


1 Answers

var result = from tq in TableQuotes
group tq by new {tq.TimeStamp.Date, tq.Symbol} into g
select g.OrderBy(tq => tq.TimeStamp).First();
like image 129
recursive Avatar answered Mar 06 '23 15:03

recursive