Skip to content

Commit 5123e6f

Browse files
Create ratio_to_report.md
1 parent 1c51582 commit 5123e6f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

ratio_to_report.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Calculating percentages using RATIO_TO_REPORT
2+
3+
RATIO_TO_REPORT Window function can be used to calculate percentage of the entire dataset or partitioned data.
4+
5+
## An illustrative example
6+
7+
Let’s look at the dataset we will be using for this tutorial:
8+
9+
```sql
10+
select
11+
player_id,
12+
team,
13+
position,
14+
goals,
15+
from soccer_players
16+
```
17+
18+
![Copy of Copy of favicon](https://github.com/user-attachments/assets/b953283b-3504-42ab-80d8-202c03d14cd7)
19+
20+
Our data is about a soccer game where each row represents a player id, with columns for id, their team, and how many goals they have scored.
21+
22+
If we wanted to work out what percentage of all goal each player has scored, we can use ratio_to_report() window function as following:
23+
24+
```sql
25+
select
26+
player_id,
27+
team,
28+
position,
29+
goals,
30+
ratio_to_report(goals) over () as overall_goals_percentage
31+
from soccer_players
32+
order by team, position;
33+
```
34+
35+
![Copy of Copy of Copy of favicon](https://github.com/user-attachments/assets/c0219bc2-6030-4fcb-a34e-c8523c48d07c)
36+
37+
38+
The over() in the query above tells the database to expand the ‘window’ in which the ratio_to_report() operates to the whole dataset.
39+
40+
The ratio_to_report() window function takes an expression (usually a column) as input and calculates the ratio of that expression to the window that is defined (in this case, the whole dataset).
41+
Using ratio_to_report() to Calculate Partitioned Percentages
42+
43+
Let’s say we were not only interested in each players overall contribution to goals, but also their contribution to goals for their specific team. We can then add a partition by to the window:
44+
45+
```sql
46+
select
47+
player_id,
48+
team,
49+
position,
50+
goals,
51+
ratio_to_report(goals) over (team) as overall_goals_percentage
52+
from soccer_players
53+
order by team, position;
54+
```
55+
56+
![Copy of favicon](https://github.com/user-attachments/assets/29fa93bc-61d8-436a-8d92-fc539fdbd243)

0 commit comments

Comments
 (0)