4

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
sooprise
  • 22,657
  • 67
  • 188
  • 276

3 Answers3

8
var result = from tq in TableQuotes
group tq by new {tq.TimeStamp.Date, tq.Symbol} into g
select g.OrderBy(tq => tq.TimeStamp).First();
recursive
  • 83,943
  • 34
  • 151
  • 241
0

This is a great resource for figuring out how to write the linq query you desire http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

Here's a straight copy of the example they give for your situation

var categories =
    from p in products
    group p by p.Category into g
    select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) };
JupiterP5
  • 318
  • 1
  • 10
0

The following will return the requested solution, the earliest quote for each company on a given day.

var results = from q in quotes
              group q by new { q.Symbol, q.TimeStamp.Date } into c
              select new TableQuote()
              {
                  Symbol = c.Key.Symbol,
                  TimeStamp = c.Min(ct => ct.TimeStamp),
                  Quote = c.OrderBy(ct => ct.TimeStamp).First().Quote
              };
sgriffinusa
  • 4,203
  • 1
  • 25
  • 26