Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 11397c0

Browse files
committed
Allow Group By of Joined table
1 parent c591cb0 commit 11397c0

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/ServiceStack.OrmLite/Expressions/SqlExpression.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,18 @@ public virtual SqlExpression<T> GroupBy(string groupBy)
457457
return this;
458458
}
459459

460-
public virtual SqlExpression<T> GroupBy<TKey>(Expression<Func<T, TKey>> keySelector)
460+
public virtual SqlExpression<T> GroupBy<Table>(Expression<Func<Table, object>> keySelector)
461+
{
462+
sep = string.Empty;
463+
useFieldName = true;
464+
465+
var groupByKey = Visit(keySelector);
466+
StripAliases(groupByKey as SelectList); // No "AS ColumnAlias" in GROUP BY, just the column names/expressions
467+
468+
return GroupBy(groupByKey.ToString());
469+
}
470+
471+
public virtual SqlExpression<T> GroupBy(Expression<Func<T, object>> keySelector)
461472
{
462473
sep = string.Empty;
463474
useFieldName = true;

tests/ServiceStack.OrmLite.Tests/UseCase/ArtistTrackSqlExpressions.cs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using NUnit.Framework;
1+
using System.Linq;
2+
using NUnit.Framework;
23
using ServiceStack.OrmLite.Tests.Support;
34
using ServiceStack.Text;
45

@@ -44,5 +45,20 @@ public void Can_Order_by_Property_Alias()
4445
Assert.That(result[1993], Is.EqualTo(2));
4546
}
4647
}
48+
49+
[Test]
50+
public void Can_Select_joined_table_with_Alias()
51+
{
52+
using (var db = CreateArtistAndTrackTablesWithData(OpenDbConnection()))
53+
{
54+
var tracksByYear = db.Dictionary<string, int>(db.From<Track>()
55+
.Join<Artist>()
56+
.GroupBy<Artist>(x => x.Name)
57+
.Select<Artist>(x => new { x.Name, Count = Sql.Count("*") }));
58+
59+
Assert.That(tracksByYear.Count, Is.EqualTo(4));
60+
Assert.That(tracksByYear.Map(x => x.Value).Sum(), Is.EqualTo(8));
61+
}
62+
}
4763
}
4864
}

0 commit comments

Comments
 (0)