0

我写信是为了在 linq 中编写这个 SQL 查询,但是没有用。

select [ProcessTime], Count([ID]) as 'amount of processes'
from [DB].[dbo].[TableX]
where [ID] in ('ServerX', 'ServerY') and [Type] ='Complete'
group by [ProcessTime]
order by [ProcessTime]

我想实现这个 linq 和我尝试过的方法,我将查询分成两部分,一个用于处理 time group by 子句,另一个用于计算 ID

var query1 =  (from a in this.db.Processes
               where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
               group a by a.ProcessTime into b
              //here I dont know where to place orderby
               select b);


 var query2 = (from a in this.db.Processes
               where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
               orderby a.ProcessTime 
               select a).Count();

这是将查询分成两部分然后将它们组合起来的正确方法吗?

4

2 回答 2

1

您可以在一个查询中完成所有这些操作:

var query1 = (from a in this.db.Processes
              where (a.ID == "ServerX" || a.ID == "ServerY") && a.Type == "Complete"
              group a by a.ProcessTime into b
              orderby b.Key
              select new {ProcessTime = b.Key, Count = b.Count()});
于 2013-04-30T06:47:45.367 回答
1

尝试这个:

var serverNames = new string[]{"ServerX", "ServerY"};
var result = db.Processes
    .Where(p => serverNames.Contains(p.ID) && p.Type == "Complete")
    .GroupBy(p => p.ProcessTime)
    .Select(g => new
    {
        ProcessTime = g.Key,
        AmountOfProcesses = g.Count()
    })
    .OrderBy(x => x.ProcessTime);
于 2013-04-30T06:45:35.507 回答