views:

29

answers:

1

Hi, I have two tables Orders and Products where Orders has a ProductID as a forgin key, I would like to select all products, if a product has orders i would like to select the one with the highest distance field.

thanks,

A: 

Hi totem,

Your question seems a bit unclear. However, I am assuming that your orders table has a 'distance' column. You would like to select all products with the order that has the highest distance value.

var products = from p in db.Products
               select new
               {
                   ProductID = p.ProductID,
                   ProductName = p.ProductName,
                   HighestDistanceOrder = p.Orders.OrderByDescending(o => o.Distance).FirstOrDefault()
               };

If you wanted the value of highest distance and not the entire order, then

var products = from p in db.Products
               select new
               {
                   ProductID = p.ProductID,
                   ProductName = p.ProductName,
                   HighestDistance = p.Orders.Max(o => o.Distance)
               };

Hope that helps.

Matrich

Matrich
wouldn't this solution actually cause mutiple sql quries?
totem
For the first case i.e. returning the order with the highest distance value, it gets all the product details first and then creates a SELECT TOP (1) query for each of the products returned.For case two which returns the highest distance value, it creates only one SQL query.
Matrich
Is there any way to do a single query but still get the full row? (Max is for a single value)
totem