Multi-dimensional cross analysis of sales data

In the previous article, we learned how to use SQL Common Table Expressions (CTE) to simplify complex query statements and implement data traversal and recursive processing.

In Chapter 13, we learned basic data grouping and summarizing operations, such as counting the number of employees and average monthly salary by department and position. Now, let us discuss some more advanced grouping statistical analysis functions, that is, the extended options of the GROUP BY clause.

Sales sample data

In this article, we will use a new sales data set (sales_data), which contains the sales of three products in three channels from January 1, 2019 to June 30, 2019. The following is part of the data in the table:

sales

We put the scripts for creating sales tables and data initialization on GitHub, click the link to download.

Now let's take a look at what advanced grouping options GROUP BY supports.

Hierarchical subtotals and totals

First of all, let's count the sales according to products and channels:

SELECT product AS "产品",
       channel AS "渠道",
       SUM(amount) AS "销售金额"
  FROM sales_data
 GROUP BY product, channel;

Guess you like

Origin blog.csdn.net/horses/article/details/108729095