Add 'avg' aggregate function

The 'AVG' aggregate function is specified in the SQL standard and
supported by MySQL, PostgreSQL, and SQLite. Include tests, too.
This commit is contained in:
Nikhil Benesch 2014-01-19 15:00:15 -05:00
parent fc01752bc8
commit 0bf4044b74
3 changed files with 34 additions and 0 deletions

View File

@ -372,6 +372,11 @@ _.extend(Builder.prototype, Common, {
return this._aggregate('sum', column); return this._aggregate('sum', column);
}, },
// Retrieve the avg of the values of a given column.
avg: function(column) {
return this._aggregate('avg', column);
},
// Increments a column's value by the specified amount. // Increments a column's value by the specified amount.
increment: function(column, amount) { increment: function(column, amount) {
return this._counter(column, amount); return this._counter(column, amount);

View File

@ -8,6 +8,12 @@ module.exports = function(knex) {
}); });
it('has an avg', function() {
return knex('accounts').logMe().avg('logins');
});
it('has a count', function() { it('has a count', function() {
return knex('accounts').logMe().count('id'); return knex('accounts').logMe().count('id');

View File

@ -22,6 +22,29 @@ module.exports = {
}] }]
} }
}, },
'has an avg': {
mysql: {
bindings: [],
sql: 'select avg(`logins`) from `accounts`',
result: [{
'avg(`logins`)': 1.6667
}]
},
postgresql: {
bindings: [],
sql: 'select avg("logins") from "accounts"',
result: [{
avg: '1.6666666666666667'
}]
},
sqlite3: {
bindings: [],
sql: 'select avg("logins") from "accounts"',
result: [{
'avg("logins")': 1.6666666666666667
}]
}
},
'has a count': { 'has a count': {
mysql: { mysql: {
bindings: [], bindings: [],