我有以下SQL查询:
goto
我发现了两个LINQ查询。
select
[Event2].EventType AS 'Event type',
SUM (1) AS 'Number of events',
AVG(DATEDIFF(Second, [Event1].CreationDate, [Event2].CreationDate)) AS 'Time'
from [Event] as [Event1]
join [Event] as [Event2] on [Event1].Id = [Event2].ParentId
group by [Event2].EventTypeId;
我必须将这些查询合并为一个。
结果必须包含三个元素:第一个事件的创建日期和第二个事件的创建日期之间经过的时间// This query brings the event types and the differences between the events.
var rows = from event1 in _eventRepository.AsQueryable()
join event2 in _eventRepository.AsQueryable() on event1.Id equals event2.ParentId
select new
{
EventId = event2.EventId,
TimeInSeconds = DbFunctions.DiffSeconds(event1.CreationDate, event2.CreationDate)
};
// This query groups the rows before by Event type.
var groups = (from item in rows
group item by item.EventTypeId into g
select new EventModel
{
EventTypeId = g.Key,
NumberOfEvents = g.Sum(x => 1),
Time = (int) g.Average(x => x.TimeInSeconds)
}).ToList();
,Event Type
,The number of events
。
答案 0 :(得分:0)
您应该只将分组语句添加到第一个查询(而不是选择):
var result = (from event1 in _eventRepository
join event2 in _eventRepository on event1.Id equals event2.ParentId
group new {
EventId = event2.EventId,
TimeInSeconds = DbFunctions.DiffSeconds(event1.CreationDate, event2.CreationDate)
}
by event2.EventTypeId into g
select new EventModel {
EventTypeId = g.Key,
NumberOfEvents = g.Count(),
Time = (int) g.Average(x => x.TimeInSeconds)
}).ToList();
您也不能在分组中指定字段,但只能在select语句中指定,但将其保留为原始