MySQL 8.0 supports window functions (Window Function), also known as analytical functions. Window functions are similar to group-by aggregate functions, but produce one result per row of data. Aggregate window functions: SUM /AVG / COUNT /MAX/MIN etc.
The case is as follows: the sales table structure and data are as follows:
Common grouping, aggregation (statistics by country)
SELECT country,sum(sum)
FROM sales
GROUP BY country
order BY country;
Window functions (summarized by country)
select year,country,product,sum,
sum(sum) over (PARTITION by country) as country_sum
from sales
order by country,year,product,sum;
Window function (calculates the tie value)
select year,country,product,sum,
sum(sum) over (PARTITION by country) as country_sum,
avg(sum) over (PARTITION by country) as country_avg
from sales
order by country,year,product,sum;
Dedicated window functions:
-
Serial number functions: ROW_NUMBER(), RANK(), DENSE_RANK()
-
Distribution functions: PERCENT_RANK(), CUME_DIST()
-
Front and back functions: LAG(), LEAD()
-
Head and tail functions: FIRST_VALUE(), LAST_VALUE()
-
Other functions: NTH_VALUE(), NTILE()
window function (ranking)
A ranking window function for calculating category rankings, and a value window function for obtaining data at a specified location
SELECT
YEAR,
country,
product,
sum,
row_number() over (ORDER BY sum) AS 'rank',
rank() over (ORDER BY sum) AS 'rank_1'
FROM
sales;
SELECT
YEAR,
country,
product,
sum,
sum(sum) over (PARTITION by country order by sum rows unbounded preceding) as sum_1
FROM
sales order by country,sum;
Of course, there are many operations that can be done, see the official website for details:
https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html