无法从“group by”获得正确的输出

时间:2014-01-31 01:36:14

标签: c# sql linq linq-to-sql group-by

尝试获取产品ID的列表,其中包含每个产品的反馈量 需要仅计算给予产品的属于特定类别的反馈(请参阅SQL脚本:categoryId == 50)。产品可以属于多个类别。

productId, cnt
14,        0
16,        0  
15,        1
09,        2
10,        2

编辑:

我想出了下面的LINQ to SQL,重新创建我通过下面的SQL脚本表达的逻辑。但结果却不尽相同。无法从SQL脚本的LINQ逻辑中得到什么不同?

LINQ to Sql:

var result = 
(
from pcl in db.productCategoryLookup
join p in db.products on pcl.productId equals p.productId
join f in db.feedbacks on p.productId equals f.feedbackId into bb
from g in bb.DefaultIfEmpty()
where (pcl.categoryId == 50)
group p by p.productId into grp
select new
{
    productId = grp.Key,
    cnt = grp.Count()
} into res1
orderby res1.cnt
select new
{
    producetId = res1.productId,
    cnt = res1.cnt
}
)
.Take(5)
.ToList();

SQL脚本:

 SELECT TOP 5
        p.productId,
        COUNT(f.feedbackId)
    FROM ProductCategoryLookup pcl
    INNER JOIN Product p
        ON p.productId = pcl.productId
    LEFT JOIN Feedbacks f
        ON f.productId = p.productId
    WHERE 
        pcl.categoryId = 50
    GROUP BY
        p.productId
    ORDER BY
        COUNT(f.feedbackId)

表:

**Products** table
productId   PK
productName  string

**ProductCategoryLookup** table. Connects products with Category.
One product can have multiple categories and the feedback goes 
for given product in given category.
productId   FK
categoryId  FK
. . .

**Feedbacks** table. Each product+category pair gets zero or more feedbacks.
feedbackId   PK
productId    FK
categoryId   FK
 . . .

**Category** table. 
categoryId   pk
name 

对于AD.Net的答案,我在'from'之后为productCategoryLookup和where子句添加了join。现在就行!感谢。

2 个答案:

答案 0 :(得分:2)

(from p in context.Products
select new {Product = p, Count = p.Feedbacks.Any() ? p.Feedbacks.Count() : 0})
.OrderBy(p=>p.Count)
.Take(5)
.Select(p=>p.Product)
.ToList()

答案 1 :(得分:0)

尝试以下查询。它可能对你有帮助。

db.Products.Select(n => new { n.ProductID, count = n.Feedbacks.Count})
                .OrderBy(m=>m.count).Take(5).ToList();