我在下面有一个SQL查询:
SELECT DISTINCT
Table1.Description,
Table2.AccountId,
COUNT(Table2.AccountId) AS Charges
FROM Table2
LEFT JOIN Table1 ON Table2.AccountId = Table1.Id
WHERE Table2.DateTime > '3/1/2014'
AND Table2.DateTime < '4/1/2014'
GROUP BY Table2.AccountId, Table1.Description
ORDER BY Charges DESC
我正在尝试将其转换为ASPX.CS代码中的LINQ查询,以填充表格并使用图表中的数据。
到目前为止我的内容如下:
var resultList = configDB.Table2
.Where(x => x.DateTime > begDate && x.DateTime < endDate)
.GroupBy(x => x.AccountID)
.Select(g => new { Account = g.Key, Charges = g.Count() })
.OrderByDescending(g => g.Charges)
.ToList();
这只是表2部分。我也试图加入表1,并且仍然可以通过我无法获得的代码来获取计费。我找到了几个帖子和解决方案来单独完成每个帖子和解决方案但不是答案,他们在分组时加入分组并加入。任何人都可以指引我使用能够帮助或指出正确方向的资源吗?
答案 0 :(得分:1)
我想出了这个(可能需要一些调整)
var resultList = Table2
.Where(x => x.DateTime > begDate && x.DateTime < endDate)
.Join(Table1, t2 => t2.AccountId, t1 => t1.Id,
(t2, t1) => new { t2.AccountId, t1.Description })
.GroupBy(x => x.AccountId)
.Select(g => new { Group = g, Charges = g.Count() })
.OrderByDescending(g => g.Charges)
.SelectMany(g => g.Group.Select(x => new { x.Description, x.AccountId, g.Charges }))
.ToList();
答案 1 :(得分:0)
尝试这样的事情:
var resultList = configDB.Table2
.Where(x => x.DateTime > begDate && x.DateTime < endDate)
.GroupJoin(configDB.Table1,
t2 => t2.AccountId,
t1 => t1.Id,
(t2, joined) => new
{
Description = joined.Select(t => t.Description).FirstOrDefault(),
AccountID = t2.AccountId,
})
.GroupBy(x => x.AccountID)
.Select(g => new
{
Account = g.Key,
Charges = g.Count(),
Description = g.Select(d=>d.Description).FirstOrDefault()
})
.OrderByDescending(g => g.Charges)
.ToList();