tags:

views:

64

answers:

3

If I have a sql table that contains

ProductID

Price

Date

and I wish to find the latest price for a given date. In Sql I can do something like

` Select * from (

select ROW_NUMBER() OVER (PARTITION BY ProductID ORDER BY Date DESC) AS row_number,

ProductID, Date, Price from ProductPrices

where date < @targetDate

) tempTable

where row_number = 1 `

Is it possible to do this easily in LinqToSql? My attempts have all ended up issuing on sql command per product?

A: 
 var result = (
               from context.table where date < targetDate 
               and ProductID = targetproduct 
               orderby date descending
               select new {ProductID, price, Date}
              ).Take(1);

Maybe the syntax is not perfect but you should pay attention to the Take(1), which is the equivalent to the row_number

despart
That finds it for a single product though, rather than the first result for *each* product.
Jon Skeet
Although it's very possible I've misread the question...
Jon Skeet
it seems that I'm the one I misread it... :)
despart
After rereading it, the body of the message does not make it clear (sorry) , but yes I was looking looking for the latest price per product.
sgmoore
A: 

How about something like this:

var query = from product in db.Products
            where product.Date < targetDate
            orderby product.Date descending
            group product by product.ProductID into groups
            select groups.First();

It's possible that calling First won't work but FirstOrDefault will - someone else found that recently in a similar situation.

EDIT: This solution was driven from the title more than from the SQL (which I don't fully understand). It aims to find the most recent entry for each product. Hope that's what you were after!

Jon Skeet
Yes, that works. It was very close to my Linq attempt with only the select statement different . I was using select new { groups.Key , details = groups.First() }which seems to trigger the multiple sql commands whereas your solution only hits the server once. So thank you very much.
sgmoore
A: 

I think this would do the job...

var qry = ProductPrices.Where(pp => pp.Date < targetDate)
                       .Max(pp => pp.Date.Ticks);
bruno conde