I want to calculate percentage of value in Group by. My table data:
id | date | artist | track | listenings |
---|---|---|---|---|
1 | 2023-01-01 | C | track_1 | 2016 |
2 | 2023-01-01 | C | track_2 | 3800 |
3 | 2023-01-01 | B | track_3 | 2311 |
4 | 2023-01-01 | A | track_4 | 4180 |
5 | 2023-01-01 | C | track_5 | 2013 |
6 | 2023-01-01 | A | track_6 | 2227 |
7 | 2023-01-01 | B | track_7 | 1006 |
8 | 2023-01-01 | B | track_8 | 720 |
9 | 2023-01-01 | A | track_9 | 2438 |
10 | 2023-01-01 | A | track_10 | 2654 |
11 | 2023-01-02 | C | track_1 | 3347 |
12 | 2023-01-02 | C | track_2 | 3100 |
13 | 2023-01-02 | B | track_3 | 2436 |
14 | 2023-01-02 | A | track_4 | 4821 |
15 | 2023-01-02 | C | track_5 | 1485 |
16 | 2023-01-02 | A | track_6 | 3157 |
17 | 2023-01-02 | B | track_7 | 1993 |
18 | 2023-01-02 | B | track_8 | 2953 |
19 | 2023-01-02 | A | track_9 | 1651 |
20 | 2023-01-02 | A | track_10 | 1260 |
I need to calculate the share of listens to the track from listenings to all tracks of one artist for each date for each of the artists. The output table must be like
id | date | artist | track | percentage |
---|---|---|---|---|
1 | 2023-01-01 | C | track_1 | 0.257 |
2 | 2023-01-01 | C | track_2 | 0.486 |
3 | 2023-01-01 | B | track_3 | 0.572 |
4 | 2023-01-01 | A | track_4 | 0.364 |
5 | 2023-01-01 | C | track_5 | 0.257 |
11 | 2023-01-02 | C | track_1 | 0.422 |
and so on. Please help me to write this script.
2
Answers
Using a subquery to find the total number of listens per artist, per date:
See fiddle
Just use window functions!