Add aggregation function to select query builder (#39)

qb: added min, max, avg, sum, and count to SelectBuilder
This commit is contained in:
SpiritOfWill
2018-05-15 15:07:35 +03:00
committed by Michał Matczuk
parent cf3a5ab95f
commit 5526e60464
2 changed files with 57 additions and 0 deletions

View File

@@ -163,3 +163,44 @@ func (b *SelectBuilder) AllowFiltering() *SelectBuilder {
b.allowFiltering = true
return b
}
// Count produces 'count(column)'.
func (b *SelectBuilder) Count(column string) *SelectBuilder {
b.fn("count", column)
return b
}
// CountAll produces 'count(*)'.
func (b *SelectBuilder) CountAll() *SelectBuilder {
b.Count("*")
return b
}
// Min produces 'min(column)' aggregation function.
func (b *SelectBuilder) Min(column string) *SelectBuilder {
b.fn("min", column)
return b
}
// Max produces 'max(column)' aggregation function.
func (b *SelectBuilder) Max(column string) *SelectBuilder {
b.fn("max", column)
return b
}
// Avg produces 'avg(column)' aggregation function.
func (b *SelectBuilder) Avg(column string) *SelectBuilder {
b.fn("avg", column)
return b
}
// Sum produces 'sum(column)' aggregation function.
func (b *SelectBuilder) Sum(column string) *SelectBuilder {
b.fn("sum", column)
return b
}
func (b *SelectBuilder) fn(name, column string) *SelectBuilder {
b.Columns(name + "(" + column + ")")
return b
}

View File

@@ -78,6 +78,22 @@ func TestSelectBuilder(t *testing.T) {
S: "SELECT * FROM cycling.cyclist_name WHERE id=? ALLOW FILTERING ",
N: []string{"expr"},
},
// Add COUNT all
{
B: Select("cycling.cyclist_name").CountAll().Where(Gt("stars")),
S: "SELECT count(*) FROM cycling.cyclist_name WHERE stars>? ",
N: []string{"stars"},
},
// Add COUNT with GROUP BY
{
B: Select("cycling.cyclist_name").Count("stars").GroupBy("id"),
S: "SELECT id,count(stars) FROM cycling.cyclist_name GROUP BY id ",
},
// Add Min
{
B: Select("cycling.cyclist_name").Min("stars"),
S: "SELECT min(stars) FROM cycling.cyclist_name ",
},
}
for _, test := range table {