如何使用LINQ或HQL执行以下SQL查询?
SELECT `year`, `month`, COUNT(code_id)
FROM (SELECT DISTINCT request_codes_id AS code_id,
YEAR(requested) AS `year`, MONTH(requested) AS `month` FROM requests) r
GROUP BY `year`, `month`
ORDER BY `year`, `month`;
我尝试了以下内容:
var items = from r in TestaccountRequest.Queryable
group r by r.RequestCodeId into g
select g.First();
var grouped = from r in items
group r by r.Requested.ToString("yyyyMM") into y
select new { Year = y.First().Requested.Year, Month = y.First().Requested.Month, Count = y.Count() };
投了一个System.String ToString(System.String) NotSupportedException
。
更新
第一个LINQ-Query中的g.First()
似乎会导致问题,因为如果我只运行第一个问题,我会得到一个Code supposed to be unreachable
- 例外,但如果我删除了.First()
它“有效”,但不会返回我需要的东西。
答案 0 :(得分:1)
按匿名类型分组:
var grouped = from r in items
group r by new { Year = r.Requested.Year,
Month = r.Requested.Month } into g
select new { g.Key.Year, g.Key.Month, Count = g.Count() };
答案 1 :(得分:0)
我有点用以下方法解决了它:
var items = from r in TestaccountRequest.Queryable
group r by r.RequestCodeId into g
select g.ElementAt(0);
var grouped = from r in items.ToList()
group r by new { Year = r.Requested.Year,
Month = r.Requested.Month } into g
select new { g.Key.Year, g.Key.Month, Count = g.Count() };
但我认为这不是最佳解决方案,因为所有对象都是从数据库中获取的,但至少它现在正在运行,但如果可用,请提供更好的解决方案。
修改强>
我现在用HQL解决了它:
HqlBasedQuery query = new HqlBasedQuery(typeof(ActivationCodeTestaccountRequestRecord),
"SELECT DISTINCT r.ActivationCodeId, YEAR(r.Requested), MONTH(r.Requested) " +
"FROM ActivationCodeTestaccountRequestRecord r");
var items = from object[] row in (ArrayList)ActiveRecordMediator.ExecuteQuery(query)
group row by new { Year = row[1], Month =row[2] } into g2
select new { Year = g2.Key.Year, Month = g2.Key.Month, Count = g2.Count() };