1

LINQ to SQL で次のクエリを作成しようとしています。このテーブルにはユーザーごとに配置されたセッションのリストが含まれており、クエリは各ユーザーの連続セッション間の平均時間を計算します。これは左結合を使用するため、セッションが 1 つしかないユーザーにはNULL値があります。

SELECT t1.workerId, AVG(DATEDIFF(s, t1.endTime, t2.startTime)) 
FROM e_userLongSessions t1 
LEFT JOIN e_userLongSessions t2 
ON t1.workerId = t2.workerId AND t1.sessionNum = t2.sessionNum - 1
GROUP BY t1.workerId
ORDER BY t1.workerId

LINQ to SQL Left Outer JoinHow to do joins in LINQ on multiple fields in single joinの質問に基づいて、次のクエリにたどり着きました。

from s1 in gzClasses.e_userLongSessions
join s2 in gzClasses.e_userLongSessions
    on new {w = s1.workerId, n = s1.sessionNum} equals new {w = s2.workerId, n = s2.sessionNum - 1}
    into joined
from s2 in joined.DefaultIfEmpty(null)
group new {s1, s2} by s1.workerId into g                   
select g.Average(e => e.s2 == null ? (double?) null : (e.s2.startTime - e.s1.endTime).TotalSeconds);

メッセージが届いていUnsupported overload used for query operator 'DefaultIfEmpty'ます。助言がありますか?

4

1 に答える 1

2

Your LINQ query is not structured the same way the T-SQL query is. Specifically, you are only including s in the grouping. In fact, s is named in a misleading way. It should be s2. Include both:

from s1 in gzClasses.e_userLongSessions                    
join s2 in gzClasses.e_userLongSessions
    on new {w = s1.workerId, n = s1.sessionNum} 
equals new {w = s2.workerId, n = s2.sessionNum - 1}
    into joined                    
from s2Null in joined.DefaultIfEmpty()                    
group new {s1, s2Null} by s1.workerId into g                    
orderby g.Key // workerId
select g.Average(e => (e.s2Null.startTime - e.s1.endTime).TotalSeconds);

Now, you have data from both tables available in the aggregate. I don't think both of your queries are taking into account that s2.startTime can be null. But that is a bug that is not the point of the question.

于 2014-03-21T22:32:24.610 に答える