【问题标题】:can't get the right output from a "group by"无法从“分组依据”获得正确的输出
【发布时间】:2014-01-31 01:36:13
【问题描述】:

尝试获取产品 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 的答案,我在 productCategoryLookup 和 where 子句的“from”之后添加了 join。现在工作!谢谢。

【问题讨论】:

  • 我现在无法理解的 COUNT 似乎有一些“魔力”
  • 真正的问题是什么?
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 实际的问题是试图获得反馈最少的前 5 名产品(不是最差的,只是反馈量)。反馈记录在反馈表中。
  • 好的,但是什么不起作用?

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


【解决方案1】:
(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()

【讨论】:

  • OP 也有一个 .ToList()
  • 谢谢,这比我的要好得多……但结果与要求的结果相差甚远。至少这给了我一个新的尝试方向!
  • 顺便问一下,你是不是故意离开 context.productCategoryLookup 的?
  • 不,如果您只想要反馈最少的产品,它应该这样做。顺便说一句,它应该只是 orderby,而不是 orderbydescending,这是另一种方式。
  • ok,那你也可以得到categoryid,按它分组,然后做orderby和take(5)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2017-03-14
    相关资源
    最近更新 更多