😺
wiki
  • Welcome, Internet Strangers!
  • sql
    • etl
      • Basics to Remember
      • Context to Remember
      • Naming Practices
      • ETL Steps
    • performance
      • Please No
      • Initial Explorations
      • Stored Procedures
    • select-tricks
      • Over Partition
      • Stored Procedures*
      • Creating Parameters
  • python
    • Working with Files
    • Classes in Python
    • Dictionaries
    • Working with Strings
    • Using Lambda
    • Seaborn
    • machine-learning
      • Learning Pandas
      • MatPlotLib! The Dreaded Line Graph...
      • matlab-qualgraphs-notes
      • Linear Regression Example
      • kNN Analysis in ScikitLearn
    • Neat Snippets
  • bash
    • helpful_cmd
  • math
    • Basic Definitions
    • Linear Regressions
    • Meaningful Sampling
Powered by GitBook
On this page

Was this helpful?

  1. sql
  2. select-tricks

Over Partition

Returning richer context

OVER PARTITION is an amazing way to generate summary data within the greater context of a table without needed an additional step to process the SQL query output.

For example, a manager wants a report of their call center agents with both their average handle time (AHT) and their department's overall AHT.

Given a table which looks like this...

ID | NAME  | DEPARTMENT | CALL_TIME
---|-------|------------|-----------
 1 | Alice | Service    | 253
 2 | Bob   | Service    | 414
 3 | Cathy | Sales      | 306

A query can be constructed to find the average handle time by agent using OVER PARTITION.

AVERAGE(t.call_time) OVER (
    PARTITION BY t.id
    ) AS 'agent_aht'
,AVERAGE(t.call_time) OVER (
    PARTITION BY t.department
    ) AS 'department_aht'
FROM table1 t

This can also be used to create running totals and averages by limiting the partition using the table row. An example would be to show the running total of an account balance over a number of different accounts.

SUM(acc.amount) OVER (
    PARTITION BY    acc.account_id
    ORDER BY        acc.datetime DESC
                    ,acc.account_id DESC
    ROWS BETWEEN    UNBOUNDED PRECEDIING --from the start
         AND        1 PRECEDING          --to this row
 )
Previousselect-tricksNextStored Procedures*

Last updated 3 years ago

Was this helpful?

These can get complex, and should be tested, but can yield a great report, especially when saved as a .

stored procedure