As you can see, this is basically a CREATE TABLE statement, with a SELECT query at the end of it.
The new table is loaded with data defined by the query in the command. The table columns have names and data types associated with the output columns of the query. The CREATE TABLE AS (CTAS) command creates a new table and evaluates the query to load the new table.
RATIO_TO_REPORT(quantity::decimal * unit_cost) is what gives us the value that we’re working with in terms of ratio; the PARTITION BY sale_date then gives us the window; these ratios need to be calculated for the day.
sale_date
salesperson
?column?
ratio_to_report
2018-05-02
Bob
26
1.0
2018-05-13
Sally
60
0.2777777777777778
2018-05-13
June
156
0.7222222222222222
2018-05-14
John
96
1.0
2018-05-25
Bob
192
0.5962732919254659
2018-05-25
Sally
130
0.40372670807453415
2018-05-26
John
156
1.0
2018-05-27
John
52
0.0962962962962963
2018-05-27
June
20
0.037037037037037035
2018-05-27
June
468
0.8666666666666667
2018-06-02
Sally
26
1.0
2018-06-03
John
60
0.2777777777777778
2018-06-03
John
156
0.7222222222222222
2018-06-12
John
96
1.0
2018-06-13
Bob
192
0.5962732919254659
2018-06-13
Sally
130
0.40372670807453415
2018-06-15
John
156
1.0
2018-06-24
Bob
52
0.7222222222222222
2018-06-24
Sally
20
0.2777777777777778
2018-06-29
John
468
1.0
ROW_NUMBER
ROW_NUMBER is a utility function that simply gives the row an ordinal value, counting up from 1; over the window.
We count the sales for the day, by applying ROW_NUMBER over the sale_date.
This article is an extension of the window function, to follow up on each of the window functions.
The LISTAGG function will aggregate values that are collected within the window defined by the partition expression.
In this example, we’ll list each sale in the database; adding a column at the end which will list all of the salespeople who made a sale on that particular day.
This article is an extension of the window function, to follow up on each of the window functions.
The LEAD function returns values in an offset row. The offset is given by the second argument to the function itself. The offset pushes the index below (or after) the selected row.
To demonstrate the effect of this function, we’ll take the sales_id value, and then we’ll also take a led sales_id. By adjusting the offset value, you’ll see how the leaded value ascends up the rows.
This article is an extension of the window function, to follow up on each of the window functions.
The LAG function returns values in an offset row. The offset is given by the second argument to the function itself. The offset pushes the index above (or before) the selected row.
To demonstrate the effect of this function, we’ll take the sales_id value, and then we’ll also take a lagged sales_id. By adjusting the offset value, you’ll see how the lagged value slips down the rows.