Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1068033
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T20:14:07+00:00 2026-05-16T20:14:07+00:00

I have a SQL query I’m having trouble creating using NHibernate Criteria: SELECT ID,

  • 0

I have a SQL query I’m having trouble creating using NHibernate Criteria:

SELECT ID, COLA, COLB, COLC
FROM table
WHERE COLC='something' AND ID IN (SELECT ID FROM (SELECT MAX(ID) as ID, COLA FROM table WHERE COLB='something' GROUP BY COLA) subquery)
ORDER BY ID DESC

I originally had this slightly simpler query:

SELECT ID, COLA, COLB, COLC
FROM table
WHERE COLC='something' AND ID IN (SELECT MAX(ID) FROM table WHERE COLB='something' GROUP BY COLA)
ORDER BY ID DESC

However, with NHibernate, if I use a “GROUP BY”, it automatically adds the field to the SELECT statement, and I have no way of stopping it (as far as I can find).

Basically, I need to find the latest record grouped by some arbitrary column (in this example, “COLA”). I’m selecting the maximum ID to try to get the latest record (though this could be something else, like “MAX(UPDATED)”). After getting the set of latest records, I’m further filtering them (“WHERE COLC=’something'”), and selecting the columns I need in the result.

If there’s a better way to get the same results, I’d be glad to hear it. My SQL skills are mediocre, at best.

In NHibernate, I could get the two queries right, but the piece in the middle – “SELECT ID FROM”, wouldn’t work.

The main query:

DetachedCriteria.For<table>()
    .Add<table>(x => x.COLC == "something")
    .Add(LambdaSubquery.Property<table>(x => x.ID).In(subquery));

And the subquery:

DetachedCriteria.For<table>()
    .Add<table>(x => x.COLB == "something")
    .SetProjection(Projections.ProjectionList()
        .Add(LambdaProjection.Max<table>(x => x.ID))
        .Add(LambdaProjection.GroupProperty<table>(x => x.COLA)));

The subquery criteria puts “COLA” in the select list (because of the GroupProperty), so it’s unusable on its own, and that’s why I need to figure out how to do the “SELECT ID FROM (SELECT …” in the criteria. When combined, they produce the following invalid SQL (because the subquery returns more than one column):

SELECT ID, COLA, COLB, COLC
FROM table
WHERE COLC='something' AND ID IN (SELECT MAX(ID), COLA FROM table WHERE COLB='something' GROUP BY COLA)
ORDER BY ID DESC

Edit: It might also help to see the kind of data and results I want:

ID  COLA  COLB          COLC
1   1     someone       someother
2   1     something     someone     (Matches subquery, but not the max. ID)
3   1     something     something   (Matches subquery and main query)
4   2     someone       something
5   2     something     someother   (Only matches subquery)
6   3     someone       someother

The result I want here are the maximum ID for a given set of “COLA”s, where “COLB” matches “something”, so I’d want the subquery to return {3, 5}. In the end, the query would only return the record for ID 3 (the outer WHERE clause weeds out the 5 because COLC is wrong). The actual data in COLB and COLC is irrelevant – I’m just using that to further filter the results.

I think, at the core of it, I want the latest record (max ID) for each set of COLA

SELECT ID, COLA, COLB
FROM table
WHERE ID IN (SELECT MAX(ID) FROM table GROUP BY COLA)
ORDER BY ID DESC
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T20:14:08+00:00Added an answer on May 16, 2026 at 8:14 pm

    I found an alternative solution since I couldn’t figure out how to get the right results using the criteria API in NHibernate – use a view instead.

    The view simply uses the query I had originally wanted (without some of the extra filtering):

    SELECT ID, COLA, COLB, COLC, ...
    FROM table
    WHERE ID IN
        (SELECT MAX(ID)
         FROM table
         GROUP BY COLA)
    

    Then, in NHibernate, I mapped the view just like a regular table (except I made it immutable):

    <class name="View" table="View" lazy="false" mutable="false">
        <id name="ID" type="Int32">
            <generator class="assigned"/>
        </id>
        <property name="COLA" type="String" length="100">
            <column name="COLA" />
        </property>
        <property name="COLB" type="String" length="100">
            <column name="COLB" />
        </property>
        <property name="COLC" type="String" length="100">
            <column name="COLC" />
        </property>
        <!-- Other fields -->
    </class>
    

    And created the class to map to:

    public class View
    {
        public virtual int ID { get; set; }
        public virtual string COLA { get; set; }
        public virtual string COLB { get; set; }
        public virtual string COLC { get; set; }
        // Other fields
    }
    

    And finally, created a query for the view:

    DetachedCriteria.For<View>()
        .Add<View>(x => x.COLB == "something")
        .Add<View>(x => x.COLC == "something")
        // Any other filtering criteria
        .AddOrder<View>(x => x.COLA, Order.Desc);
    

    I’d have rather used a single criteria query in NHibernate, but this got the job done.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i have sql query select * from Roles Join Users On Roles.Role=Users.RoleId it return
i have this sql query select * from table where name like ? but
I have an sql query like this: SELECT IF( (SELECT COUNT(*) FROM `test_table2` WHERE
I have this SQL query from the logs select content = 5%id%201=1 from pages
I have Sql query: SELECT News.NewsId, News.Subject, Cm.Cnt FROM dbo.News LEFT JOIN (SELECT Comments.OwnerId,
I have this sql query Dim cmd As OleDbCommand = New OleDbCommand(SELECT * FROM
I have folowing sql query select sta_name Station,count(factory_name) as factories from gps1 group by
i have this sql query: SELECT b.topbid, b.topdate, a.* FROM auction_items a LEFT JOIN
I have sql query like this: select a.x, a.y, sum(a.foo) as foo_sum from a
I have SQL Select query with where clauses. For e.g select * from table

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.