【问题标题】:Group by not including "null" data按不包括“空”数据分组
【发布时间】:2021-05-05 19:51:06
【问题描述】:

我正在尝试计算状态统计信息,但问题是当我进行分组时,我没有得到 "null" 统计信息。

Parent:
Id   Status
1    Processed
2    Hold
3    Review
4    Closed
5    Rejected
6    Draft

Child :
Id    UserId    ParentId
1     100       1
2     100       1
3     100       1
4     100       1

5     100       2
6     100       2
7     100       2

8     100       3
4     100       3

8     100       4
4     100       4

9     100       5
10    100       6

11    100       null
12    100       null

预期输出:

Processed = 4
Hold = 3
Review = 2
Closed = 2
Rejected = 1
Draft = 1
Null = 2

查询:

var data = (from c in context.Child
            where c.UserId == 100 &&
            (c.Parent ==null || c.Parent.IsActive)
            group c by new
            {
                c.ParentId,
                c.Parent.Status
            } into g
            select new StatusWiseStatsResult
            {
                Status = g.Key.Status,
                Statistics = g.Count(),
                Id = g.Key.ParentId == null ? 0 : (int)g.Key.ParentId
            }).OrderByDescending(c => c.Statistics).ToList();

但它不会在上述查询中返回 2 的“空”计数。

谁能告诉我是什么问题和解决方法?

【问题讨论】:

  • 不是你的问题,而是where c.UserId == 100 && c.UserId == 100,你有这个条件两次;也许是 o 型?
  • @Codexer 抱歉,这是一个错字。感谢您指出。更新了问题:)
  • 这是哪个数据库提供商?我尝试使用 EF6 + Sql Server 进行类似查询,但无法重现。
  • @GertArnold 我正在使用 Sql Server
  • 这是来自您的代码库的确切查询吗?其他谓词可以很容易地将外连接变成事实上的内连接。

标签: c# entity-framework linq entity-framework-6


【解决方案1】:

在这里看到这一行

 (c.Parent ==null || c.Parent.IsActive)

拿出来。然后检查是否 c.Parent.IsActive != false

 .Where(x => c.Parent != null ? c.Parent.IsActive : true)

【讨论】:

  • 抱歉,如果我删除 c.Parent=null 那么它不包括 ParentId 为 null 的数据,但我想要所有数据,即使 Parent Id 为 null。
  • @ILoveStackoverflow 哦——我想我错过了阅读它,因为您想排除 null 的情况,如果您希望包含 null,那么您无法检查 parent 在原始查询中是否处于活动状态
  • 是的,我想包含“null”计数,而这个“null”是我查询中的问题。 Bdw,我没有否决你的答案,所以你知道:)
  • 哦,谢谢 - 是的,我有超过 60k 的时间关心否决票的日子已经一去不复返了。
猜你喜欢
  • 2011-12-21
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多