Skip to main content

Summarise values into new rows

Values can be summarised and displayed in dedicated rows. This is helpful to display observations alongside statistics in the table. SUMMARISE can be repeated to compute multiple summaries.

Clause syntax

SUMMARISE [GROUP | GRAND] <operation> OF <columns>, ...
  SETTING <parameter> => <value>, ...

Also accepts the spelling SUMMARIZE.

Scope

[GROUP | GRAND]

The scope directly following the SUMMARISE clause determines which rows the operation aggregates over. Setting the scope to GROUP will compute the summary for each group determined by FACET clauses separately. The GRAND scope will compute the summary for all rows. Without spelling out a scope, the default will be GROUP. When no groups are declared by FACET and the scope is set to GROUP, all rows are treated as belonging to the same group. The difference between a FACET-less GROUP scope and a GRAND scope is largely a difference in style and label spanning. A query result with no rows cannot be summarised: SUMMARISE errors on an empty table.

Operation

<operation>

This part of the clause can be an identifier or a string representing an expression. The identifiers are the same ones used in stat aggregation in plots. When using an identifier, one of the following operations are available:

Name Description Numeric Date(time) Other
count Number of rows ✓ ✓ ✓
n_distinct Number of distinct values ✓ ✓ ✓
n_missing Number of nulls ✓ ✓ ✓
sum Sum ✓
prod Product ✓
min Minimum ✓ ✓
max Maximum ✓ ✓
range max − min ✓ ✓
mid (min + max) / 2 ✓ ✓
mean Arithmetic mean ✓ ✓
geomean Geometric mean ✓
harmean Harmonic mean ✓
rms Root-mean-square ✓
median Median ✓ ✓
sdev Standard deviation (population, ÷ n) ✓ ✓
se Standard error (population, ÷ n) ✓ ✓
var Variance (population, ÷ n) ✓
iqr Interquartile range ✓ ✓
p05 5th percentile ✓ ✓
p10 10th percentile ✓ ✓
p25 25th percentile ✓ ✓
p50 50th percentile (median) ✓ ✓
p75 75th percentile ✓ ✓
p90 90th percentile ✓ ✓
p95 95th percentile ✓ ✓

When using a string as an expression, you can use any of the identifiers in curly braces. For example '{mean}' will display the mean via expression. The expressions can be used to display multiple metrics in a single cell, e.g. '{median} ({p25}, {p75})' will display the median and interquartile range in one cell. Inside the brackets, you can use limited arithmetic. The operands include the operation identifiers listed above (like mean, sdev), numeric literals (2, 0.5) and scientific notation (1e6). The +, - unary operators and +, -, * and / binary operators and (/) parentheses for grouping. For example you can use '({mean - 1.96 * se}, {mean + 1.96 * se})' to display a 95% confidence interval (assuming normal distribution) in parentheses separated by a comma. If any placeholder in a string expression comes out null (see missing below), the whole cell comes out null.

For the naked, non-string identifiers the formatting of the cell values is applied externally via FORMAT clauses. The string expressions can be self-formatting via the same syntax as scale breaks. A string-expression cell ignores a FORMAT wildcard label, but direct labels still apply — including null => … to replace a null result. All summary metrics are assumed to be numeric. As such, the :num formatter is implied and does not need to be written out in full. The expression '{mean:%.2f}' will display the mean with two decimal points in printf-style. Other formatters can be used, e.g. {max:bytes} to display base-1024 size. When using arithmetic, the formatting is placed at the end and is applied to the result so that '{mean + sdev:%.2f}' rounds the expression to two decimals.

Date and timestamp columns accept the order statistics (min, max, mid, mean, median and the percentiles), returning a date or timestamp, and range, sdev, se and iqr, returning a duration. A date or timestamp renders as ISO text or via :time ('{min:time %d %b %Y}'); in arithmetic it becomes a plain number: days for dates, seconds for timestamps — so '{max-min:duration d}' renders a date range as a duration. A date-valued mean or mid rounds to the nearest whole day.

Column selection

OF <columns>, ...

The SUMMARISE clause requires a comma-separated list of columns to aggregate. The columns must be part of the TABULATE selection. The ‘counting’ operations listed above can be applied to columns of any type, the order and dispersion statistics also accept date and timestamp columns, and the remaining operations require numeric columns.

Settings

SETTING <parameter> => <value>

The SETTING sub-clause is typical with key-value pairs. It currently takes the following parameters:

  • place: the location of the summary rows relative to the body rows they summarise. Can be 'top' to place the summary rows at the top of each group or table, or 'bottom' (default) to place the summary rows after the body rows.
  • rowlabel: A string for the label of the summary row. The default null falls back to printing the operation, where string expression operations are displayed without formatting details.
  • missing: A string option for how to treat null values in the table. The default 'propagate' will list any non-counting operation as null, while the tallies count and n_missing include null-rows — note that n_distinct is not a tally and comes out null when the column contains any. Can be set to 'drop' to explicitly ignore null values in aggregates and ignore these rows in counting operations.
  • blank: A string displayed in cells of the summary row whose column are not summarised. The default is an em dash ('—'); set it to '' for empty cells.

Examples

A summary without groups will summarise all rows.

CREATE TEMP TABLE my_data AS 
SELECT DISTINCT ON (species, island, sex) * FROM ggsql:penguins
WHERE bill_len IS NOT NULL AND sex IS NOT NULL

TABULATE * FROM my_data
SUMMARISE mean OF bill_len, bill_dep
speciesislandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.516.71783250female2007
GentooBiscoe50.016.32305700male2007
ChinstrapDream46.517.91923500female2007
AdelieTorgersen39.517.41863800female2007
AdelieBiscoe37.818.31743400female2007
AdelieTorgersen39.118.71813750male2007
AdelieBiscoe37.718.71803600male2007
AdelieDream37.218.11783900male2007
GentooBiscoe46.113.22114500female2007
ChinstrapDream50.019.51963900male2007
mean——42.317.5————

A grand summary will always summarise all rows, and is displayed with a stronger border.

TABULATE * FROM my_data
SUMMARISE GRAND mean OF bill_len, bill_dep
speciesislandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.516.71783250female2007
GentooBiscoe50.016.32305700male2007
ChinstrapDream46.517.91923500female2007
AdelieTorgersen39.517.41863800female2007
AdelieBiscoe37.818.31743400female2007
AdelieTorgersen39.118.71813750male2007
AdelieBiscoe37.718.71803600male2007
AdelieDream37.218.11783900male2007
GentooBiscoe46.113.22114500female2007
ChinstrapDream50.019.51963900male2007
mean——42.317.5————

Groups can be specified using FACET.

TABULATE * FROM my_data
FACET island
SUMMARISE mean OF bill_len, bill_dep
speciesbill_lenbill_depflipper_lenbody_masssexyear
BiscoeGentoo50.016.32305700male2007
Adelie37.818.31743400female2007
Adelie37.718.71803600male2007
Gentoo46.113.22114500female2007
mean—42.916.6————
DreamAdelie39.516.71783250female2007
Chinstrap46.517.91923500female2007
Adelie37.218.11783900male2007
Chinstrap50.019.51963900male2007
mean—43.318.0————
TorgersenAdelie39.517.41863800female2007
Adelie39.118.71813750male2007
mean—39.318.0————

The labels of summary rows compose with regular body row labels in the stub.

TABULATE * FROM my_data
FACET island
FORMAT STUB species
SUMMARISE mean OF bill_len, bill_dep
bill_lenbill_depflipper_lenbody_masssexyear
BiscoeGentoo50.016.32305700male2007
Adelie37.818.31743400female2007
Adelie37.718.71803600male2007
Gentoo46.113.22114500female2007
mean42.916.6————
DreamAdelie39.516.71783250female2007
Chinstrap46.517.91923500female2007
Adelie37.218.11783900male2007
Chinstrap50.019.51963900male2007
mean43.318.0————
TorgersenAdelie39.517.41863800female2007
Adelie39.118.71813750male2007
mean39.318.0————

The display of the label in the stub can be changed using the rowlabel setting.

TABULATE * FROM my_data
FACET species
SUMMARISE mean OF bill_len, bill_dep
  SETTING rowlabel => 'Average'
islandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.516.71783250female2007
Torgersen39.517.41863800female2007
Biscoe37.818.31743400female2007
Torgersen39.118.71813750male2007
Biscoe37.718.71803600male2007
Dream37.218.11783900male2007
Average—38.518.0————
ChinstrapDream46.517.91923500female2007
Dream50.019.51963900male2007
Average—48.218.7————
GentooBiscoe50.016.32305700male2007
Biscoe46.113.22114500female2007
Average—48.014.8————

The display of non-summary cells can be changed using the blank setting. Using an empty string ('') leaves these cells empty.

TABULATE * FROM my_data
FACET species
SUMMARISE mean OF bill_len, bill_dep
  SETTING blank => ''
islandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.516.71783250female2007
Torgersen39.517.41863800female2007
Biscoe37.818.31743400female2007
Torgersen39.118.71813750male2007
Biscoe37.718.71803600male2007
Dream37.218.11783900male2007
mean38.518.0
ChinstrapDream46.517.91923500female2007
Dream50.019.51963900male2007
mean48.218.7
GentooBiscoe50.016.32305700male2007
Biscoe46.113.22114500female2007
mean48.014.8

The summary cells are subject to FORMAT when using plain identifiers, along with the body rows.

TABULATE * FROM my_data
FACET species
FORMAT bill_len, bill_dep LABEL * => '{:num %.2f}'
SUMMARISE mean OF bill_len, bill_dep
islandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.5016.701783250female2007
Torgersen39.5017.401863800female2007
Biscoe37.8018.301743400female2007
Torgersen39.1018.701813750male2007
Biscoe37.7018.701803600male2007
Dream37.2018.101783900male2007
mean—38.4717.98————
ChinstrapDream46.5017.901923500female2007
Dream50.0019.501963900male2007
mean—48.2518.70————
GentooBiscoe50.0016.302305700male2007
Biscoe46.1013.202114500female2007
mean—48.0514.75————

To specifically format the summary values, you can use the expression string form.

TABULATE * FROM my_data
FACET species
SUMMARISE '📏 {mean:%.2f}' OF bill_len, bill_dep
islandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.516.71783250female2007
Torgersen39.517.41863800female2007
Biscoe37.818.31743400female2007
Torgersen39.118.71813750male2007
Biscoe37.718.71803600male2007
Dream37.218.11783900male2007
📏 mean—📏 38.47📏 17.98————
ChinstrapDream46.517.91923500female2007
Dream50.019.51963900male2007
📏 mean—📏 48.25📏 18.70————
GentooBiscoe50.016.32305700male2007
Biscoe46.113.22114500female2007
📏 mean—📏 48.05📏 14.75————

You can use repeated summaries. The order in which the summaries are declared determine the order of the rows.

TABULATE * FROM my_data
SUMMARISE p25 OF bill_len, bill_dep
SUMMARISE p50 OF bill_len, bill_dep
SUMMARISE p75 OF bill_len, bill_dep
speciesislandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.516.71783250female2007
GentooBiscoe50.016.32305700male2007
ChinstrapDream46.517.91923500female2007
AdelieTorgersen39.517.41863800female2007
AdelieBiscoe37.818.31743400female2007
AdelieTorgersen39.118.71813750male2007
AdelieBiscoe37.718.71803600male2007
AdelieDream37.218.11783900male2007
GentooBiscoe46.113.22114500female2007
ChinstrapDream50.019.51963900male2007
p25——38.116.9————
p50——39.518.0————
p75——46.418.6————

Or display related summaries in a single cell.

TABULATE * FROM my_data
SUMMARISE '{p50:%.2f} ({p25:%.2f}, {p75:%.2f})' OF bill_len, bill_dep
speciesislandbill_lenbill_depflipper_lenbody_masssexyear
AdelieDream39.516.71783250female2007
GentooBiscoe50.016.32305700male2007
ChinstrapDream46.517.91923500female2007
AdelieTorgersen39.517.41863800female2007
AdelieBiscoe37.818.31743400female2007
AdelieTorgersen39.118.71813750male2007
AdelieBiscoe37.718.71803600male2007
AdelieDream37.218.11783900male2007
GentooBiscoe46.113.22114500female2007
ChinstrapDream50.019.51963900male2007
p50 (p25, p75)——39.50 (38.12, 46.40)18.00 (16.88, 18.60)————

When data contains ‘null’ values, they propagate to aggregate metrics (but not necessarily count metrics). Notice how the summary of bill_len comes out as ‘null’.

SELECT species, island, sex,
       CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len,
       bill_dep, flipper_len, body_mass
FROM my_data

TABULATE *
SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep
speciesislandsexbill_lenbill_depflipper_lenbody_mass
AdelieDreamfemale39.516.71783250
GentooBiscoemalenull16.32305700
ChinstrapDreamfemale46.517.91923500
AdelieTorgersenfemale39.517.41863800
AdelieBiscoefemalenull18.31743400
AdelieTorgersenmale39.118.71813750
AdelieBiscoemalenull18.71803600
AdelieDreammale37.218.11783900
GentooBiscoefemalenull13.22114500
ChinstrapDreammale50.019.51963900
mean———null17.48——

You can ignore ‘null’ values by using the missing => 'drop' setting.

SELECT species, island, sex,
       CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len,
       bill_dep, flipper_len, body_mass
FROM my_data

TABULATE *
SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep
  SETTING missing => 'drop'
speciesislandsexbill_lenbill_depflipper_lenbody_mass
AdelieDreamfemale39.516.71783250
GentooBiscoemalenull16.32305700
ChinstrapDreamfemale46.517.91923500
AdelieTorgersenfemale39.517.41863800
AdelieBiscoefemalenull18.31743400
AdelieTorgersenmale39.118.71813750
AdelieBiscoemalenull18.71803600
AdelieDreammale37.218.11783900
GentooBiscoefemalenull13.22114500
ChinstrapDreammale50.019.51963900
mean———41.9717.48——

Date and timestamp columns can be summarised with the order statistics, formatted with :time, and range gives their span as a duration.

CREATE TEMP TABLE launches AS
SELECT * FROM (VALUES
    ('Alpha', DATE '2024-01-15'),
    ('Alpha', DATE '2024-02-10'),
    ('Beta',  DATE '2024-03-01'),
    ('Beta',  DATE '2024-03-20')) AS t(product, launched)

TABULATE * FROM launches
FACET product
SUMMARISE '{min:time %d %b %Y} – {max}' OF launched
  SETTING rowlabel => 'Dates'
SUMMARISE '{range:duration d}' OF launched
  SETTING rowlabel => 'Duration'
launched
Alpha2024-01-15
2024-02-10
Dates15 Jan 2024 – 2024-02-10
Duration26d
Beta2024-03-01
2024-03-20
Dates01 Mar 2024 – 2024-03-20
Duration19d