diff --git a/lib/builder.js b/lib/builder.js index 267595bb..3842169d 100644 --- a/lib/builder.js +++ b/lib/builder.js @@ -372,6 +372,11 @@ _.extend(Builder.prototype, Common, { 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. increment: function(column, amount) { return this._counter(column, amount); diff --git a/test/integration/builder/aggregate.js b/test/integration/builder/aggregate.js index a6802871..ee0dd1c7 100644 --- a/test/integration/builder/aggregate.js +++ b/test/integration/builder/aggregate.js @@ -8,6 +8,12 @@ module.exports = function(knex) { }); + it('has an avg', function() { + + return knex('accounts').logMe().avg('logins'); + + }); + it('has a count', function() { return knex('accounts').logMe().count('id'); diff --git a/test/integration/output/Aggregate.js b/test/integration/output/Aggregate.js index 69e589fb..280d0040 100644 --- a/test/integration/output/Aggregate.js +++ b/test/integration/output/Aggregate.js @@ -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': { mysql: { bindings: [],