Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expressions in the ORDER BY list cannot contain aggregate functions. #3575

Open
mehranrezaei opened this issue Jul 2, 2024 · 4 comments
Open

Comments

@mehranrezaei
Copy link

I create a simple query like below:

var query = session.Query<VariantRecord>()
    .GroupBy(x => x.ProductId)
    .Select(g => new { ProductId = g.Key, MinPrice = g.Min(p => p.Price) })
    .OrderBy(o => o.MinPrice)
    .ToList();

I get error Expressions in the ORDER BY list cannot contain aggregate functions.
The generates SQL looks like below:

select
        variantrec0_.ProductId  as col_0_0_,
        min(variantrec0_.Price)  as col_1_0_
from
        VariantRecord variantrec0_
group by
        variantrec0_.ProductId  
order by
        min(variantrec0_.Price) asc

I get error because it does not use the alias (col_1_0_) in order-by clause.

What is the solution?

@hazzik
Copy link
Member

hazzik commented Jul 2, 2024

This depends on your DB. Solution would likely be to order in memory.

@mehranrezaei
Copy link
Author

My table contains millions of records, it is not possible to sort in memory.

As I mentioned above, a query like below works correctly. I don't think it depends on the database. The problem is that NHibernate does not pay attention to the defined alias.

select
        variantrec0_.ProductId  as col_0_0_,
        min(variantrec0_.Price)  as col_1_0_
from
        VariantRecord variantrec0_
group by
        variantrec0_.ProductId  
order by
        col_1_0_ asc

@hazzik
Copy link
Member

hazzik commented Jul 2, 2024

You're welcome to submit a PR with fixes. The problem is with your RDBMS dialect that does not support this: other RDBMS do support the SQL generated by NHibernate in this case.

@mehranrezaei
Copy link
Author

One goal of using an ORM is coding uniformity for different databases. I use SQL CE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants