Running Count

April 4, 2018

Running Count

In SQL, a window function allows us to perform aggregate functions on a set of query rows. While an aggregate function groups query rows as a single row result, a window function produces a result for each query row.

In this article, we will demonstrate how we can retrieve a running count of items within a class of product.

We will be using the classicmodels database, which you can download from mysqltutorial for this article.


Running Count, by Product Line

Our goal is to come up with a running count, for each unique product line. For brevity, we will be using a subset of the products table.


SELECT
   productName,
   productLine 
FROM
   products 
WHERE
   productLine IN 
   (
      'Trains',
      'Planes'
   )
ORDER BY
   productLine ASC;
productName productLine
1980s Black Hawk Helicopter Planes
P-51-D Mustang Planes
1928 British Royal Navy Airplane Planes
1900s Vintage Bi-Plane Planes
Corsair F4U ( Bird Cage) Planes
1900s Vintage Tri-Plane Planes
American Airlines: B767-300 Planes
America West Airlines B757-200 Planes
ATA: B757-300 Planes
F/A 18 Hornet 172 Planes
American Airlines: MD-11S Planes
Boeing X-32A JSF Planes
Collectable Wooden Train Trains
1950’s Chicago Surface Lines Streetcar Trains
1962 City of Detroit Streetcar Trains

The ROW_NUMBER() function allows us to generate a running count. Do note that it must be paired with the OVER(PARTITION BY ...) clause.


SELECT
   productName,
   productLine,
   ROW_NUMBER() OVER(PARTITION BY productLine) AS rowNumber 
FROM
   products 
WHERE
   productLine IN 
   (
      'Trains',
      'Planes'
   )
ORDER BY
   productLine ASC,
   rowNumber ASC;
productName productLine rowNumber
1980s Black Hawk Helicopter Planes 1
P-51-D Mustang Planes 2
1928 British Royal Navy Airplane Planes 3
1900s Vintage Bi-Plane Planes 4
Corsair F4U ( Bird Cage) Planes 5
1900s Vintage Tri-Plane Planes 6
American Airlines: B767-300 Planes 7
America West Airlines B757-200 Planes 8
ATA: B757-300 Planes 9
F/A 18 Hornet 172 Planes 10
American Airlines: MD-11S Planes 11
Boeing X-32A JSF Planes 12
Collectable Wooden Train Trains 1
1950’s Chicago Surface Lines Streetcar Trains 2
1962 City of Detroit Streetcar Trains 3
comments powered by Disqus