LogoLogo
HomeAPIBlog
3.0.0-SNAPSHOT
3.0.0-SNAPSHOT
  • INTRODUCTION
    • Getting Started
      • Running Local Development Servers
      • Beginner Tutorial: Hello World
      • Beginner Tutorial: Hello Database
      • Tutorial: Wheels, AJAX, and You
    • Frameworks and Wheels
    • Requirements
    • Manual Installation
    • Upgrading
    • Screencasts
  • Command Line Tools
    • CLI Overview
    • Quick Start Guide
    • Command Reference
      • Core Commands
        • wheels init
        • wheels info
        • wheels reload
        • wheels deps
        • wheels destroy
        • wheels watch
      • Code Generation
        • wheels generate app
        • wheels generate app-wizard
        • wheels generate controller
        • wheels generate model
        • wheels generate view
        • wheels generate property
        • wheels generate route
        • wheels generate resource
        • wheels generate api-resource
        • wheels generate frontend
        • wheels generate test
        • wheels generate snippets
        • wheels scaffold
      • Database Commands
        • wheels dbmigrate info
        • wheels dbmigrate latest
        • wheels dbmigrate up
        • wheels dbmigrate down
        • wheels dbmigrate reset
        • wheels dbmigrate exec
        • wheels dbmigrate create blank
        • wheels dbmigrate create table
        • wheels dbmigrate create column
        • wheels dbmigrate remove table
        • wheels db schema
        • wheels db seed
      • Testing Commands
        • wheels test
        • wheels test run
        • wheels test coverage
        • wheels test debug
      • Configuration Commands
        • wheels config list
        • wheels config set
        • wheels config env
      • Environment Management
        • wheels env
        • wheels env setup
        • wheels env list
        • wheels env switch
      • Plugin Management
        • wheels plugins
        • wheels plugins list
        • wheels plugins install
        • wheels plugins remove
      • Code Analysis
        • wheels analyze
        • wheels analyze code
        • wheels analyze performance
        • wheels analyze security
      • Security Commands
        • wheels security
        • wheels security scan
      • Performance Commands
        • wheels optimize
        • wheels optimize performance
      • Documentation Commands
        • wheels docs
        • wheels docs generate
        • wheels docs serve
      • CI/CD Commands
        • wheels ci init
      • Docker Commands
        • wheels docker init
        • wheels docker deploy
      • Deployment Commands
        • wheels deploy
        • wheels deploy audit
        • wheels deploy exec
        • wheels deploy hooks
        • wheels deploy init
        • wheels deploy lock
        • wheels deploy logs
        • wheels deploy proxy
        • wheels deploy push
        • wheels deploy rollback
        • wheels deploy secrets
        • wheels deploy setup
        • wheels deploy status
        • wheels deploy stop
    • CLI Development Guides
      • Creating Commands
      • Service Architecture
      • Migrations Guide
      • Testing Guide
  • Working with Wheels
    • Conventions
    • Configuration and Defaults
    • Directory Structure
    • Switching Environments
    • Testing Your Application
    • Using the Test Environment
    • Contributing to Wheels
    • Submitting Pull Requests
    • Documenting your Code
  • Handling Requests with Controllers
    • Request Handling
    • Rendering Content
    • Redirecting Users
    • Sending Files
    • Sending Email
    • Responding with Multiple Formats
    • Using the Flash
    • Using Filters
    • Verification
    • Event Handlers
    • Routing
    • URL Rewriting
      • Apache
      • IIS
      • Tomcat
      • Nginx
    • Obfuscating URLs
    • Caching
    • Nesting Controllers
    • CORS Requests
  • Displaying Views to Users
    • Pages
    • Partials
    • Linking Pages
    • Layouts
    • Form Helpers and Showing Errors
    • Displaying Links for Pagination
    • Date, Media, and Text Helpers
    • Creating Custom View Helpers
    • Localization
  • Database Interaction Through Models
    • Object Relational Mapping
    • Creating Records
    • Reading Records
    • Updating Records
    • Deleting Records
    • Column Statistics
    • Dynamic Finders
    • Getting Paginated Data
    • Associations
    • Nested Properties
    • Object Validation
    • Object Callbacks
    • Calculated Properties
    • Transactions
    • Dirty Records
    • Soft Delete
    • Automatic Time Stamps
    • Database Migrations
      • Migrations in Production
    • Using Multiple Data Sources
  • Plugins
    • Installing and Using Plugins
    • Developing Plugins
    • Publishing Plugins
  • Project Documentation
    • Overview
  • External Links
    • Source Code
    • Issue Tracker
    • Sponsor Us
    • Community
Powered by GitBook
LogoLogo
On this page
  • Counting Rows
  • Getting an Average
  • Getting the Highest and Lowest Values
  • Getting the Sum of All Values
  • Grouping Your Results

Was this helpful?

Edit on GitHub
Export as PDF
  1. Database Interaction Through Models

Column Statistics

Use Wheels to get statistics on the values in a column, like row counts, averages, highest values, lowest values, and sums.

PreviousDeleting RecordsNextDynamic Finders

Last updated 1 month ago

Was this helpful?

Since Wheels simplifies so much for you when you select, insert, update, and delete rows from the database, it would be a little annoying if you had to revert back to using cfquery and COUNT(id) AS x type queries when you wanted to get aggregate values, right?

Well, good news. Of course you don't need to do this; just use the built-in functions , , , and .

Let's start with the function, shall we?

Counting Rows

To count how many rows you have in your authors table, simply do this:

authorCount = model("author").count();

What if you only want to count authors with a last name starting with "A"? Like the function, will accept a where argument, so you can do this:

authorCount = model("author").count(where="lastName LIKE 'A%'");

Simple enough. But what if you wanted to count only authors in the USA, and that information is stored in a different table? Let's say you have stored country information in a table called profiles and also setup a hasOne / belongsTo association between the author and profile models.

Just like in the function, you can now use the include argument to reference other tables.

In our case, the code would end up looking something like this:

authorCount = model("author").count(include="profile", where="countryId=1 AND lastName LIKE 'A%'");

Or, if you care more about readability than performance, why not just join in the countries table as well?

authorCount = model("author").count(include="profile(country)", where="name='USA' AND lastName LIKE 'A%'");

In the background, these functions all perform SQL that looks like this:

MySQL
SELECT COUNT(*)
FROM authors
WHERE ...

However, if you include a hasMany association, Wheels will be smart enough to add the DISTINCT keyword to the SQL. This makes sure that you're only counting unique rows.

For example, the following method call:

authorCount = model("author").count(include="books", where="title LIKE 'Wheels%'");

Will execute this SQL (presuming id is the primary key of the authors table and the correct associations have been setup):

MySQL
SELECT COUNT(DISTINCT authors.id)
FROM authors LEFT OUTER JOIN books ON authors.id = books.authorid
WHERE ..

Getting an Average

The same goes for the remaining column statistics functions as well; they all accept the property argument.

Here's an example of getting the average salary in a specific department:

avgSalary = model("employee").average(property="salary", where="departmentId=1");

You can also pass in distinct=true to this function if you want to include only each unique instance of a value in the average calculation.

Getting the Highest and Lowest Values

They are pretty self explanatory, as you can tell by the following examples:

highestSalary = model("employee").maximum("salary");
lowestSalary = model("employee").minimum("salary");

Getting the Sum of All Values

Let's wrap up this chapter on a happy note by getting the total dollar amount you've made:

howRichAmI = model("invoice").sum("billedAmount");

Grouping Your Results

All of the methods we've covered in this chapter accepts the group argument. Let's build on the example with getting the average salary for a department above, but this time, let's get the average for all departments instead.

avgSalaries = model("employee").average(property="salary", group="departmentId");

When you choose to group results like this you get a cfquery result set back, as opposed to a single value.

Limited Support

The group argument is currently only supported on SQL Server and MySQL databases.

OK, so now we've covered the function, but there are a few other functions you can use as well to get column statistics.

You can use the function to get the average value on any given column. The difference between this function and the function is that this operates on a single column, while the function operates on complete records. Therefore, you need to pass in the name of the property you want to get an average for.

To get the highest and lowest values for a property, you can use the and functions.

The last of the column statistics functions is the function.

As you have probably already figured out, adds all values for a given property and returns the result. You can use the same arguments as with the other functions (property, where, include, and distinct).

sum()
minimum()
maximum()
average()
count()
count()
findAll()
count()
findAll()
count()
average()
count()
count()
minimum()
maximum()
sum()
sum()