我正在编写在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&我试过的,我将查询分成两个,一个用于处理时间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();
这是将查询拆分为两个然后再合并它们的正确方法吗?
答案 0 :(得分: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);
答案 1 :(得分: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()});