简体   繁体   中英

Need help for complex SQL query in NHibernate

I need to know how I can rewrite the following SQL query in NHibernate's ICriteria format. It is basically a way to mimic the MS-SQL's RANK() feature and return only those results that are most current.

SELECT a.Name, a.Value, a.CreationDate
FROM MyTable a
WHERE EXISTS
(
  SELECT NULL
  FROM
  (
    SELECT TOP 1 CreationDate
    FROM MyTable
    WHERE Name = a.Name
    ORDER BY CreationDate DESC
  ) b
  WHERE b.CreationDate = a.CreationDate
)

For example, given a table with the following data:

NAME, VALUE, CREATIONDATE
'Key One', 'value one v1', '2009-11-11'
'Key One', 'value one v2', '2009-11-12'
'Key Two', 'value two v1', '2009-11-09'
'Key Three', 'value three v2', '2009-09-09'
'Key Three', 'value three v1', '2009-09-06'
'Key Three', 'value three v3', '2009-10-01'

The results of the above query would be:

'Key One', 'value one v2', '2009-11-12'
'Key Two', 'value two v1', '2009-11-09'
'Key Three', 'value three v3, '2009-10-01'

When the query to complex, don't use "Criteria API" but "HQL", you can be lose a lot of time to find the right solution with "Criteria API". The query you show can almost be use without change. Look at this : https://www.hibernate.org/hib_docs/nhibernate/html/queryhql.html

At the end the code generated is, in general, the same with "Criteria API" or "HQL" ...

A piece of code :

StringBuilder query = new StringBuilder();
query.Append("from MyTable where ");
query.Append("DateOfDayStart <= :startDate and DateOfDayEnd >= :endDate ");
IList<MyTable> list = session.CreateQuery(query.ToString())
    .SetDateTime("startDate", startDate)
    .SetDateTime("endDate", endDate)
    .List<MyTable>();
return list;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM