如何在linq中将此语句写入sql

时间:2016-05-06 16:41:41

标签: linq

SELECT TOP (5) 
    Sales.Product, Sales.Product_Price, COUNT(*) AS CNT, 
    Products.Category, Products.IMG_URL, Products.Rate_Avg
FROM          
    Sales 
INNER JOIN
    Products ON Sales.Product = Products.Product
GROUP BY      
    Sales.Product, Sales.Product_Price, 
    Products.Category, Products.IMG_URL, Products.Rate_Avg
HAVING        
    (COUNT(*) > 1)
ORDER BY      CNT DESC

1 个答案:

答案 0 :(得分:1)

该查询的大多数与等效的linq-to-sql表达式具有一对一的对应关系。虽然TOP (5)部分需要添加到最后。

(from s in db.Sales
join p in db.Products on s.Product equals p.Product
group s by new { s.Product, s.Product_Price, p.Category, p.IMG_URL, p.Rate_Avg } into g
where g.Count() > 1
orderby g.Count() descending
select new
{
    g.Key.Product,
    g.Key.Product_Price,
    CNT = g.Count(),
    g.Key.Category,
    g.Key.IMG_URL,
    g.Key.Rate_Avg,
}).Take(5)