【问题标题】:How to left join to another left join如何左连接到另一个左连接
【发布时间】:2015-04-08 18:58:54
【问题描述】:

我有一张存放库存物品的桌子。这些库存商品具有以下属性

public class StockItem
{
    public int BrandId { get; set; }
    public int ModelId { get; set; }
    public decimal Price { get; set; }
    public int StoreId { get; set; }
}

其中 StoreId 可以是 1(Store A)或 2(Store B

我想对这些项目进行分组以获得以下结果

BrandId
ModelId
Count in Store A
count in Store B

我以前使用过group by 子句,但不是这样。我应该如何编写 linQ 语句来完成我的任务?

总结一下我有以下记录

Id   BrandId   ModelId   Price   StoreId
=========================================
1       1         1       11        1
2       1         1       11        1
3       1         2       12        1
4       1         2       12        2
5       1         1       11        2

并试图得到以下结果

BrandId   ModelId   CountInStoreA   CountInStoreB
=================================================
    1        1            2               1
    1        2            1               1

【问题讨论】:

标签: c# linq entity-framework group-by


【解决方案1】:
var result = from item in db.Items
          group item by new { item.BrandId, item.ModelId, item.TotalPrice }
          into gr
          select new 
          {
              gr.Key.BrandId,
              gr.Key.ModelId,
              gr.Key.TotalPrice,
              CountA = gr.Count(it => it.StoreId == 1),
              CountB = gr.Count(it => it.StoreId == 2),
          }

【讨论】:

  • 非常感谢您的帮助。但是,如果我使用具有内部和外部联接的多个表,并且需要同时使用来自多个表/对象的参数进行分组呢?
  • @user4591106 请更新您的问题,详细解释您的方案。
  • 在该主题上进行更多工作并进行广泛搜索,我找到了下一个问题的解决方案。但我感谢您有意提供进一步帮助。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
相关资源
最近更新 更多