tags:

views:

47

answers:

3
select p.Id, sum(inc.Quantity) 
from Products p join Incomes inc
group by p.Id 
order by sum(inc.Quantity) >0

This query gives NHibernate.Hql.Ast.ANTLR.QuerySyntaxException on ORDER BY clause. I wonder is it possible to overcome this error and perform sorting by some expression?

UPDATE
I need to sort products list by name, price etc. BUT products with quantity == 0 must go to the bottom of the list (no matter what name, price it has). Also I need to perform paging of that list.

A: 

It's a while since I've done any NHibernate, but I'd have expected you to at least want to remove the > 0 bit of the ordering:

order by sum(inc.Quantity)

or possibly use an alias:

select p.Id, sum(inc.Quantity) totalQuantity
from Products p join Incomes inc
group by p.Id 
order by totalQuantity

I don't know if that'll work, but it's worth a shot :)

Jon Skeet
I don't want to remove "> 0" part beacause I want to perform sorting by THAT boolean flag (product is available - products total quantity > 0). I've also tried using aliases - they don't work
kilonet
@kilonet: Surely if you sort by the normal quantity that *will* effectively sort by whether or not the product is in stock: 0 will come before any positive values.
Jon Skeet
still, when sorting by sum (unlike boolean expression) I can't perform additional sorting by price or by name for example
kilonet
@kilonet: In this case you can't sort by price or by name because those aren't aggregates - it's more to do with the *grouping* than anything else. If you could give detail of what you're really trying to do, that would help.
Jon Skeet
thanks, I updated my question
kilonet
A: 

Try

select p.Id, sum(inc.Quantity) 
from Products p join Incomes inc
group by p.Id 
having sum(inc.Quantity) > 0
order by sum(inc.Quantity)

Order by is used for sorting. To filter on aggregated fields use having.

See http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-grouping

Andreas Paulsson
+1  A: 

You need a syntax that is supported by SQL too. This works:

select p.Id, sum(inc.Quantity) 
from Products p join p.Incomes inc
group by p.Id 
order by case when sum(inc.Quantity) > 0 then 0 else 1 end

Nitpicking: why do your entities have plural names?

Diego Mijelshon