无法在多列和计数上分组

时间:2013-08-29 01:59:47

标签: c# linq count group-by linq-to-entities

我想用Linq编写这个简单的查询:

select issuercode,securitycode,dataprocessingflag,COUNT(issuercode) as cnt 
from cmr_invhdr
where ProcessedLike <> 'STMNT ONLY'
group by issuercode,securitycode,dataprocessingflag
order by Issuercode

我尝试了以下代码,但是我收到了这个错误(DbExpressionBinding需要一个带有ResultType集合的输入表达式。 参数名称:输入):

 var lstCMRInvHdrNips = (from r in e.CMR_INVHDR
                         where r.ProcessedLike != "STMNT ONLY"
                         select new { 
                                        r.IssuerCode, 
                                        r.SecurityCode, 
                                        CountofIssuerCode = r.IssuerCode.Count(),
                                        r.DataProcessingFlag 
                                    }
                         ).GroupBy(x => 
                                       new { 
                                               x.IssuerCode, 
                                               x.SecurityCode, 
                                               x.DataProcessingFlag, 
                                               x.CountofIssuerCode 
                                           }
                                   ).OrderBy(x => x.Key.IssuerCode).ToList();

1 个答案:

答案 0 :(得分:2)

在对此字段进行分组时,是否有任何意义可以统计issuercode?当按字段分组时,COUNT始终为1。

您可能不应按issuercode进行分组,并在单独的GroupBy声明中Select后计算:

var result = e.CMR_INVHDR
              .Where(r => r.ProcessedLike != "STMNT ONLY")
              .GroupBy(r => new { r.SecurityCode, r.DataProcessingFlag })
              .Select(r => new 
              { 
                  Value = r.Key, 
                  IssuerCodesCount = r.GroupBy(g => g.IssuerCode).Count() 
              })
              .ToList();