// SQL snippet

Dominant-value frequency table

One GROUP BY produces the frequency table; a windowed sum over the group counts turns the counts into percentages.

Main statement
All engines

The task

orders.status should be five known values, but is it? A frequency table shows every value that exists, how often it appears, and what share of the table each one owns.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT status,
       COUNT(*) AS order_count,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct_of_table
FROM orders
GROUP BY status
ORDER BY order_count DESC;

工作原理

GROUP BY status counts rows per value; SUM(COUNT(*)) OVER () sums those group counts across all groups (the table total) inside the same query. Multiplying by 100.0 first forces decimal division, so the percentage keeps its fraction. The result is a ranked, percent-share profile of the column.

Variations

Top value only (LIMIT: PostgreSQL, MySQL, SQLite)

SELECT status, COUNT(*) AS order_count
FROM orders
GROUP BY status
ORDER BY order_count DESC
LIMIT 1;

Without window functions (any engine, MySQL 5.7 included)

MySQL
SELECT status,
       COUNT(*) AS order_count,
       ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM orders), 1) AS pct_of_table
FROM orders
GROUP BY status
ORDER BY order_count DESC;

Questions that come up

Why 100.0 and not 100?

PostgreSQL, SQL Server and SQLite divide integers as integers: 100 * 2 / 14 is 14, not 14.3, and a category with 1 row out of 300 shows 0. The decimal literal 100.0 turns the whole expression into decimal arithmetic before the division. MySQL and Oracle always return a fraction from /, so there it changes nothing, and it keeps the query portable.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.