Question

My question is subtly different to other questions I have seen here on StackOverflow, so please do not confuse this with previous answers.

I have a query

SELECT tab1.Id 
  FROM TABLE1 tab1 
  WHERE tab1.modified_date between to_date('01/04/2013 10:00:00', 'dd/mm/yyyy HH:MI:SS') and to_date('01/04/2013 11:15:00', 'dd/mm/yyyy HH:MI:SS') 
  GROUP BY tab1.Id
  ORDER BY max(tab1.received_date) desc

I would like to select the TOP 500 rows, and because Oracle processes a where clause before the GROUP and ORDER BY conditions (evidence), I must achieve this by wrapping this query in another to select the top 500.

So, now my query looks like...

SELECT * 
FROM (SELECT tab1.Id 
  FROM TABLE1 tab1 
  WHERE tab1.modified_date between to_date('01/04/2013 10:00:00', 'dd/mm/yyyy HH:MI:SS') and to_date('01/04/2013 11:15:00', 'dd/mm/yyyy HH:MI:SS') 
  GROUP BY tab1.Id
  ORDER BY max(tab1.received_date) desc ) sub 
WHERE ROWNUM <=500      

This all works great, but I am struggling to translate this into an NHibernate query using the QueryOver API. The inner query is simple, e.g.

var subquery = QueryOver.Of<Table1>()
            .Select(Projections.Group<Table1>(e => e.Id))
            .....where clause
            .OrderBy(Projections.Max<Table1>(e => e.Received_Date)).Desc

but how do i wrap this in a select * from subquery where rownum <= 500?

Was it helpful?

Solution 2

The problem that prevented me using the Take() method suggested in the previous answers was due to the ORDER BY part of my statement. The ORDER BY was being evaluated after the Take(), which meant the wrong 500 results were being returned.

I worked around the problem by creating a view representing my query that contained the ORDER BY clause, and then the Take() method works as expected when selecting from the view.

OTHER TIPS

NHibernate knows how to create a correct query that selects the top x rows.

  • HQL and plain SQL queries: query.SetMaxResults(500).
  • QueryOver and Linq queries: query.Take(500).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top