I am trying to count the groups of query resulted from Group by clause, but I can't seem to get the count of each group using ICriteria.
My entity:
public class PageView
{
#region public fields
public virtual int PagelogID { get; set; }
public virtual string PageTitle { get; set; }
public virtual string UserID { get; set; }
public virtual DateTime DateViewed{get;set;} --->Map to Date_Viewed column
public virtual string SessionID { get; set; }
public virtual string UserGroup { get; set; }
#endregion
}
I want to group the data by the year/month based on the DateViewed. Such result can be achieved by the following query:
select extract(year from DATE_VIEWED) "year", extract(month from DATE_VIEWED) "month", count(*) from PAGEVIEW_LOG where date_viewed > to_date(add_months(sysdate,-12))
group by extract(year from DATE_VIEWED), extract(month from DATE_VIEWED)
order by "year", "month" desc;
This is my Criteria:
ProjectionList pl = Projections.ProjectionList();
this.crit.Add(Expression.Gt("DateViewed", DateTime.Now.AddMonths(-12)));
pl.Add(Projections.SqlGroupProjection(
"Extract(month from Date_Viewed) MONTH",
"Extract(month from Date_Viewed)",
new String[] { "MONTH" },
new NHibernate.Type.IType[] { NHibernateUtil.Int32 }), "MONTH");
pl.Add(Projections.SqlGroupProjection(
"Extract(year from Date_Viewed) YEAR",
"Extract(year from Date_Viewed)",
new String[] { "YEAR" },
new NHibernate.Type.IType[] { NHibernateUtil.Int32 }), "YEAR");
//pl.Add(Projections.Count("*"));
this.crit.SetProjection(pl);
this.crit.AddOrder(Order.Desc("YEAR"));
this.crit.AddOrder(Order.Desc("MONTH"));
This successfully gives me everything I wanted besides the "Count(*)" part of the query.
What I have tried:
1: Add p1.Add(Projections.Count("YEAR")
:
This gives me error as the Nhibernate doesn't recognize YEAR as a column despite I gave it an alias.
2: Add p1.Add(Projections.Count("*")
:
Same result as above
3: Store the SqlGroupProjection for year column into a variable: IProjection yearProjection
and add **p1.Add(Projections.Count(yearProjection)
This gives me error for "length has to be greater than 0" error;
4: pl.Add(Projections.Count(Projections.RowCount()))
No luck either
what am I missing here? How do I add Count(*) to the criteria?
I was very close:
Instead of doing: pl.Add(Projections.Count(Projections.RowCount()))
This should be:
pl.Add(Projections.RowCount())
;