Help with NHibernate Criteria query groupby property

1.3k views Asked by At

I have the below query,

SearchTemplate Template = new SearchTemplate();
            Template.Criteria = DetachedCriteria.For(typeof(table1));

            Template.Criteria.CreateCriteria("table2", "Usr", NHibernate.SqlCommand.JoinType.InnerJoin)

                 .SetProjection(Projections.ProjectionList()
                 .Add(Projections.Count("Usr.ID"), "UserCount")
                  .Add(Projections.GroupProperty("Location"), "ALocation")
                  .Add(Projections.GroupProperty("Company"), "ACompany")
                  .Add(Projections.GroupProperty("Usr.Designation"), "ADesignation"));  

The above query gives me data as,

Location   Company    Designation   Count
  Florida      A          Manager       3
  Florida      A          QA            5
  Texas        B          Manager       6
  Texas        B          QA            7

Is there a way to change the query so that it gives data as,

  Location   Company    Manager    QA               
  Florida      A           3       5
  Texas        B           6       7

Here Manager and QA are the only possible values that can go into Designation field..

1

There are 1 answers

1
Diego Mijelshon On BEST ANSWER

Instead of

.Add(Projections.Count("Usr.ID"), "UserCount")
.Add(Projections.GroupProperty("Usr.Designation"), "ADesignation")

You'll need two projections, one per result column:

.Add(Projections.Sum(Projections.Conditional(
                                 Restrictions.Eq("Usr.Designation", "Manager"),
                                 Projections.Constant(1),
                                 Projections.Constant(0)))
.Add(Projections.Sum(Projections.Conditional(
                                 Restrictions.Eq("Usr.Designation", "QA"),
                                 Projections.Constant(1),
                                 Projections.Constant(0)))