How to create summation with "sum" with multiple queryover columns

Asked

Viewed 449 times

1

People need to create a query with queryOver(Nhibernate) C#, to add more than one column. Example in pure sql:

SELECT SUM(coluna1 + coluna2 + coluna3 + coluna4)
FROM tabela

First I did so:

Tabela tabela = null;
Session.QueryOver<Tabela>(() => tabela)
           .Select(Projections.Sum<Tabela>(t => t.coluna1))
           .Select(Projections.Sum<Tabela>(t => t.coluna2))
           .Select(Projections.Sum<Tabela>(t => t.coluna3))
           .Select(Projections.Sum<Tabela>(t => t.coluna4))

But this way we sum each column and generates 4 columns, I would like to sum all and generate only one column.

2 answers

2


Solution based in this OS response.

You can use Projections.SqlFunction, to apply a projection customized in Projections.Sum, using the NHibernate.Dialect.Function.VarArgsSQLFunction to inform the SQL bind template.

Something similar to the following example:

Tabela itemAlias = null;

var query = Session.QueryOver<Tabela>(() => itemAlias)
    .Select(Projections.Sum(
        Projections.SqlFunction(
            new NHibernate.Dialect.Function.VarArgsSQLFunction("(", " + ", ")"),
            NHibernateUtil.Double,
            Projections.Property(() => itemAlias.coluna1),
            Projections.Property(() => itemAlias.coluna2),
            Projections.Property(() => itemAlias.coluna3),
            Projections.Property(() => itemAlias.coluna4)
        )
    )
);

var result = query.SingleOrDefault<double>();

The SQL generated by this query will be something simulate to this (depending on the database):

select sum((THIS_.COLUNA1 + THIS_.COLUNA2 + THIS_.COLUNA3 + THIS_.COLUNA4)) as Y0_
from TABELA THIS_ 
  • 1

    Just what I needed, it worked right, thanks for the help!

0

I can’t think of a "Nhibernate" way to do this. The solution would be to execute a pure query

var query = "select C.prop1 + C.prop2 from Classe as C";

var sum = session.CreateQuery(query).UniqueResult<double>();

Edit:

Maybe you can try this way

Session.QueryOver<Table>(() => tabela)
   .Select(Projections.Sum<Table>(t => t.Prop1 + t.Prop2 + t.Prop3 + t.Prop4));
  • Thanks for the answer, but that way I knew, I needed msm with queryOver. @jbueno.

  • You use Nhibernate with Linq?

  • Use also. I edited the question and put as I was doing earlier with queryOver, but that way generates 4 columns.

  • Check out the @Marcosvinicius edition

  • I did it this way, I can’t seem to put more than one column. Has exception: Message=the variable’t' of type Table' is referenced in scope '', but it is not defined.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.