I need to select fields from unique records within a table with multiple where clauses. I currently am using C# and LINQ fluent syntax connected with NHibernate. So I am wondering if there is a way to create this query that way. Here is a test dataset:
+----+----------+------+------+ | Id | ParentId | Name | Type | +----+----------+------+------+ | 1 | 100 | A | 1 | | 2 | 100 | A | 2 | | 3 | 100 | A | 3 | | 4 | 200 | B | 1 | | 5 | 300 | A | 1 | | 6 | 300 | A | 2 | | 7 | 400 | A | 1 | | 8 | 400 | A | 2 | | 9 | 400 | A | 3 | | 10 | 400 | A | 4 | +----+----------+------+------+
I can get the results I want using this SQL query:
SELECT ParentId, COUNT(Name) as Cnt, Max(Id) as Id, Max(Name) as Name, Max(Type) as Type FROM TestGroupBy Where Name = 'A' Group By ParentId;
This gives the result:
+----------+-----+----+------+------+ | ParentId | Cnt | Id | Name | Type | +----------+-----+----+------+------+ | 100 | 3 | 3 | A | 3 | | 300 | 2 | 6 | A | 2 | | 400 | 4 | 10 | A | 4 | +----------+-----+----+------+------+
I know how to make the group by query but I can't figure out how to do the multiple MAX selects. Is that just not possible with LINQ? If it's not, then what would be a way that I could go about this?
When you have a queryable, you can call
Selectand pass a predicate. Thenewkeyword constructs an object with the schema you prefer.