使用objectFactory在C#中加入2个单独的LINQ查询

时间:2012-12-11 07:50:50

标签: c# sql linq join

我正在尝试实现以下SQL查询,它以我需要的方式进入LINQ。我加入了2个单独的SQL查询,如果组价格大于单个价格,则选择产品。我正在使用LINQ to objects并为Purchases and Products表提供Object Factory。

select DISTINCT(a.Name) from
(select p.Prod_ID, p.Name, SUM(p.Price) as Total
from Tb_AvailableProduct p, Tb_Purchases o
where p.Prod_ID = o.Prod_ID
group by p.Prod_ID, p.Name) a
JOIN
(select p.Prod_ID, p.Price
from Tb_AvailableProduct p, Tb_Purchases o
where p.Prod_ID = o.Prod_ID) b
on a.Prod_ID = b.Prod_ID
where a.Total > b.Price

我在Linq有第一个查询,但我只想选择一个产品名称,如果该产品的团体价格高于产品的个别价格......即已销售多个产品。我试图通过总和并且不使用计数来实现这一点。

from o in this.myObjectFactory.ThePurchases
join p in this.myObjectFactory.TheProducts.Values
on o.ProductID equals p.ProductID
where o.CustomerID == customer.CustomerID
group p by p.ProductID into query1
select new { ProductID = query1.Key, TotalPurchasesThisYear = query1.Sum (p => p.Price)});

1 个答案:

答案 0 :(得分:1)

这样的事情应该可行(它与你的SQL查询非常相似):

var result = 
    from a in
        (
            from p in TheProducts
            join o in ThePurchases
            on p.ProductID equals o.ProductID
            group p by new { p.ProductID, p.Name, p.Price } into g
            select new
            {
                ProductID = g.Key.ProductID,
                Name = g.Key.Name,
                Total = g.Sum(i => i.Price)
            }
        )
    join b in
        (
            from p in TheProducts
            join o in ThePurchases
            on p.ProductID equals o.ProductID
            select new
            {
                ProductID = p.ProductID,
                Price = p.Price
            }
        )
    on a.ProductID equals b.ProductID
    where a.Total > b.Price
    select a.Name;

result = result.Distinct();