在linq中得到错误的总和和数

时间:2016-07-23 14:03:34

标签: c# linq

这是我的表结构

ID   A     B     C     D

1    null  10    5     null
2    3     5     null  D2
3    8     null  2     D2
4    null  4     3     D1
5    4     6     1     D2

这是c#类及其存储查询结果的属性。

public class GrillTotals
{
        public int? SumOfA {get; set;}

        public int? SumOfB{get; set;}

        public int? SumOfC{get; set;}

        public int? CountOfD1{get; set;}

        public int? CountOfD2{get; set;}
}

我的期望是:

SumOfA = 15
SumOfB = 20
SumOfC = 11
CountOfD1 = 1
CountOfD2 = 3  

我得到的是:     SumOfA = null,     SumOfB = null,     SumOfC = null,     CountOfD1 = 0,     CountOfD2 = 0

这是我尝试过的代码。

var _FinalResult = from s in dbContext.tblSchedules
 group s by new
 {
     s.A,
     s.B,
     s.C,
     s.D,
 } into gt
 select new GrillTotals
 {
     SumOfA = gt.Sum(g => g.A),
     SumOfB = gt.Sum(g => g.B),
     SumOfC = gt.Sum(g => g.C),
     CountOfD1 = gt.Count(g => g.D == "D1"),
     CountOfD2 = gt.Count(g => g.D == "D2"),
 };

如果我做错了什么或做错了,请尝试纠正我。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您不应该按要计算聚合的字段进行分组。当你按它们分组时,每个聚合(Sum,Min,Max等)都将返回值本身(并根据条件返回Count 1或0)。

从我看到你试图通过单个SQL查询返回多个聚合。如果这是正确的,可以使用 group by constant 技术。

只需替换

class ViewPrezentacje(blobstore_handlers.BlobstoreDownloadHandler, BaseHandler):
    def get(self,blob_key):
        blob_key = str(urllib.unquote(blob_key))
        blob_info=blobstore.BlobInfo.get(blob_key)
        self.send_blob(blob_info, save_as=urllib.quote(blob_info.filename.encode('utf-8')))

 group s by new
 {
     s.A,
     s.B,
     s.C,
     s.D,
 } into gt

答案 1 :(得分:0)

试试这个:

 var _FinalResult = from s in dbContext.tblSchedules
 group s by new
 {
     s.A,
     s.B,
     s.C,
     s.D,
 } into gt
 select new GrillTotals
 {
     SumOfA = gt.Sum(g => g.A ?? 0),
     SumOfB = gt.Sum(g => g.B ?? 0),
     SumOfC = gt.Sum(g => g.C ?? 0),
     CountOfD1 = gt.Count(g => g.D == "D1"),
     CountOfD2 = gt.Count(g => g.D == "D2"),
 };