【发布时间】:2018-03-20 08:48:22
【问题描述】:
我的 join 语句需要很多帮助,因为它会使我尝试加入的两个表的行相乘:
我的样本数据:
SAPId CompendiumId Seats
----- ------------ -----
1 443 21
2 443 22
3 443 23
4 443 24
5 443 25
6 571 25
7 352 20
QBId CompendiumId Slots
----- ------------ -----
1 443 26
2 443 27
3 571 25
4 571 23
我想要的输出是:
CompendiumId Seats Slots
------------ ----- -----
443 115 53
571 25 48
352 20 0
但我的代码的结果是:
CompendiumId Seats Slots
------------ ----- -----
443 230 265
571 50 48
我认为这里发生的情况是这样的,其中以红色突出显示的单元格是重复的单元格:
这是我的代码:
控制器
private MyContext db = new MyContext();
public ActionResult Index()
{
var sapsummarylist = (from cmp in db.Compendia
join sp in db.SAPs on cmp.Id equals sp.CompendiumId
join qb in db.QualificationBatches on cmp.Id equals qb.CompendiumId
group new { cmp.Id, sp.Seats, qb.Slots } by new { cmp.Id } into mgrp
from grp in mgrp.DefaultIfEmpty()
select new SAPSummaryViewModel
{
Id = grp.Id,
Seats = mgrp.Sum(x => x.Seats),
Slots = mgrp.Sum(x => x.Slots)
});
return View(sapsummarylist.Distinct());
}
模型
public class Compendium
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<QualificationBatch> QualificationBatches { get; set; }
public virtual ICollection<SAP> SAPs { get; set; }
}
public class QualificationBatch
{
public int Id { get; set; }
public int CompendiumId { get; set; }
public int Slots { get; set; }
public virtual Compendium Compendium { get; set; }
}
public class SAP
{
public int Id { get; set; }
public int CompendiumId { get; set; }
public int Seats { get; set; }
public virtual Compendium Compendium { get; set; }
}
视图模型
public class SAPSummaryViewModel
{
public int Id { get; set; } //Compendium
public int Slots { get; set; } //QualificationBatch
public int Seats { get; set; } //SAP
}
【问题讨论】:
-
嗨。请阅读minimal reproducible example 并采取行动。为该输出提供约束(PK、唯一性、FK)和输入和所需的输出。用文字解释输出如何是输入的函数。在 left join 之前,你得到了你期望的结果吗? “因为这两个实体彼此不相关”是什么意思?请use text, not images/links, for text (including code, tables & ERDs)。使用图片只是为了方便补充文本和/或无法在文本中给出的内容。
-
嗨。桌子有帮助。 “这里发生的事情是这样的”尚不清楚。在您的左连接之前,您已经通过连接删除了两个表中都不存在的 cmp id 的行。努力获得部分结果。您想要两个单独的左连接的连接,每个左连接都有自己的组/聚合,但您的查询不要求这样做。通过加入两次,您可以生成每一行,这些行可以由第一次加入中的一行组合而成——它本身没有 id 作为键——当你继续加入 on一个非键。查看部分结果!找到好的子表达式! PSminimal reproducible example 表示我们可以剪切&粘贴&运行代码。
-
这似乎是多个聚合连接的典型错误编程。一个想要加入two MAX/inner aggregations 的SQL 示例。一个想要加入two GROUP_CONCAT/left aggregations 的SQL 示例——更类似于您的SUM,因为NULL 加0。我没有费心去寻找一个更面向asp 的示例。强迫自己总是用谷歌搜索你的问题/问题/目标的许多清晰、简洁和特定的版本/措辞,有和没有你的字符串,并阅读很多答案。你还没有清楚地说明问题。
标签: asp.net-mvc join left-join inner-join outer-join