我正在尝试将以下查询转换为linQ表达式:
SELECT t1.lastchanged,
currentstatus,
(SELECT count(ID)
FROM [Issues] t2
WHERE t2.CurrentStatus = t1.currentstatus and t2.lastchanged <= t1.lastchanged) AS running_total
FROM [Issues] t1
GROUP BY t1.lastchanged, currentstatus
ORDER BY t1.lastchanged
到目前为止,我做了以下事情:
var statusCounts = models.GroupBy(x => new { x.CurrentStatus, x.LastChanged })
.Select(g => new { g.Key, Count = g.Count() })
.ToList();
有什么建议吗?
答案 0 :(得分:1)
为了拥有嵌套选择,就像在sql中一样,再次从model
集合中选择。
var statusCounts = models.GroupBy(x => new { x.CurrentStatus, x.LastChanged })
.Select(g => new
{
CurrentStatus = g.Key.CurrentStatus,
LastChanged = g.Key.LastChanged,
Count = models.Count(m => m.CurrentStatus == g.Key.CurrentStatus &&
m.LastChanged <= g.Key.LastChanged)
})
.OrderBy(item => item.Key.LastChanged);
或者在查询语法中:
var statusCounts = from t1 in models
group t1 by new { x.CurrentStatus, x.LastChanged } into g
orderby g.Key.LastChanged
select new
{
CurrentStatus = g.Key.CurrentStatus,
LastChanged = g.Key.LastChanged,
Count = models.Count(m => m.CurrentStatus == g.Key.CurrentStatus &&
m.LastChanged <= g.Key.LastChanged)
};