使用order by子句在LINQ中对函数进行分组

时间:2014-04-03 08:24:11

标签: c# sql-server linq

如果有人可以帮我解决问题,我会很感激:

在t-SQL中:

SELECT REP_SEQ, CLASS_ID, CLASS_NAME, GROUP_ID, GROUP_NAME, CODE_ID, CODE_NAME, SUM(AMOUNT),DATE
FROM REPORTS.dbo.[table]
WHERE DATE = '2014-04-01'
GROUP BY REP_SEQ, CLASS_ID, CLASS_NAME, GROUP_ID, GROUP_NAME, CODE_ID, CODE_NAME, DATE
ORDER BY DATE, REP_SEQ, CLASS_ID, GROUP_ID, CODE_ID

我尝试在LINQ中编写此查询:

var query = from e in context.table
                        where e.DATE == '2014-04-01'
                        group e by new { e.REP_SEQ, 
                                         e.CLASS_ID, 
                                         e.CLASS_NAME, 
                                         e.GROUP_ID, 
                                         e.GROUP_NAME, 
                                         e.CODE_ID, 
                                         e.CODE_NAME,
                                         e.DATE } into res                     
                        select new { res.Key.REP_SEQ, 
                                     res.Key.CLASS_ID, 
                                     res.Key.CLASS_NAME, 
                                     res.Key.GROUP_ID,
                                     res.Key.GROUP_NAME,
                                     res.Key.CODE_ID,
                                     res.Key.CODE_NAME,
                                     res.Sum(e=>e.AMOUNT).Value,
                                     res.Key.DATE };

我不确定它是否正确。我还需要添加ORDER BY子句。

提前多多感谢

1 个答案:

答案 0 :(得分:0)

如果您想获得table的列表,可以将结果投影为table

var query = context.table
.Where(t => t.DATE == '2014-04-01')
.GroupBy(e => new {e.REP_SEQ, 
                   e.CLASS_ID,
                   e.CLASS_NAME, 
                   e.GROUP_ID, 
                   e.GROUP_NAME, 
                   e.CODE_ID, 
                   e.CODE_NAME,
                   e.DATE
                  })
.Select(res => new table
                  { 
                     REP_SEQ = res.Key.REP_SEQ, 
                     CLASS_ID = res.Key.CLASS_ID, 
                     CLASS_NAME = res.Key.CLASS_NAME, 
                     GROUP_ID = res.Key.GROUP_ID,
                     GROUP_NAME =res.Key.GROUP_NAME,
                     CODE_ID = res.Key.CODE_ID,
                     CODE_NAME = res.Key.CODE_NAME,
                     AMOUNT = res.Sum(e=>e.AMOUNT),
                     DATE = res.Key.DATE 
                  })
.OrderBy(r = r.DATE)
.ThenBy(r => r.REP_SEQ)
.ThenBy(r => r.CLASS_ID)
.ThenBy(r => r.GROUP_ID)
.ThenBy(r => r.CODE_ID)
.ToList();