c# - Linq 查询以在多个条件下连接表 C#
问题描述
我是编写 Linq 查询的新手,想编写如下查询。
关于要求的简要信息:
我需要为连接到另一个具有其名称的表的用户获取不同组键的计数
TABLE - 1: Table - 2:
--------------- -------------
| Id | GrpKey | prdId | UserId| | Id | GrpKey | GrpName | UserId
| 1 | 123455 | Test1 | 11111 | 1 | 123455 | GroupOne | 1111
| 2 | 123455 | Test2 | 22222 | 2 | 551234 | GroupTwo | 1111
| 3 | 123455 | Test3 | 22222
| 4 | 551234 | Test4 | 11111
| 5 | 551234 | Test5 | 11111
| 6 | DBNULL | Test4 | 11111
| 7 | DBNULL | Test5 | 11111
REQD. RESULT for UserId : 11111
--------------------------------
GrpKey | GrpName | Count(GrpKey)
DBNULL | DBNULL | 2
551234 | GroupTwo| 2
123455 | GroupOne| 1
Queries Tried:
1)
from grp in table2
join item in table1 on grp.GrpKey equals item.GrpKey into j1
where grp.UserId == "1111"
select new Group
{
Count = j1.Count(),
Name = grp.GrpName,
Key = grp.GrpKey,
}).ToList();
2)
var result = (from item in table1
join grp in table2 on item.GrpKey equals grp.GrpKey into j1
from rt in j1.DefaultIfEmpty()
where item.userId == userId
select new Group
{
GrpKey = item.GrpKey,
userId = item.userId,
Count = j1.Count(),
GrpName = rt.GroupName
}).ToList();
TriedQuery1 的问题:
使用上面的 LINQ 查询,我可以获得除 GrpKey 和 GrpName 为 NULL 的行之外的所有值的计数。任何人都可以帮我查询以根据我所需的数据集获取数据吗
TriedQuery2 的问题:
即使有值为 NULL 的行,具有 null 或为零的行数。
提前致谢
解决方案
对于第二个查询,您可以为左连接结果添加Group by,如以下代码:
var result = (from item in table1
join grp in table2 on item.GrpKey equals grp.GrpKey into j1
from rt in j1.DefaultIfEmpty()
where item.userId == 11111
group rt by rt?.GrpKey into g
select new
{
GrpKey = g.Key,
GrpName = g.First()?.GrpName,
Count = g.Count(),
}).ToList();
我希望你觉得这有帮助。
推荐阅读
- android - 出现数据库,但无法过滤或搜索数据
- sql - Rank 分区中的情况
- angular - 订阅服务
- python - TypeError:不可散列的类型:'list' | 将 Odoo v8 移植到 Odoo 12
- java - 为什么要使用其属性绘制多个对象,而第二个对象使用先前的对象值?
- database - 何时从数据库中删除过期行?
- reactjs - 如何确定字符串是否是 Typescript 中的 keyof 接口?
- python - 列表中的字典 Python
- javascript - 如何在 Typescript 中序列化/反序列化复杂对象,例如反序列化对象与被序列化的对象类型相同
- google-maps-api-3 - 有没有办法改变谷歌方向api中道路名称的字体大小