开发者

How to distinct select and group with castle active records?

How can I execute开发者_运维技巧 the following SQL-Query using LINQ or HQL?

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`;

I tried the following:

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() };

which threw a System.String ToString(System.String) NotSupportedException.

UPDATE:

The g.First() in the first LINQ-Query seems to cause the problem, because if I only run the first one I get a Code supposed to be unreachable-Exception, but if I remove the .First() it "works", but does not return what I need.


Group by an anonymous type instead:

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() };


I kinda solved it using the following:

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() };

but I gues thats not the best solution as all objects are getting fetched from the DB, but at least it is working for now, but please provide a better solution if available.

EDIT:
I now solved it using 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() };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜