I have a table as below:
-------------------------------------------------------------------------------------
| Name | Singer | ID |
-------------------------------------------------------------------------------------
| Stay,Love Yourself,Crazy In Love | Justin Bieber,Justin Bieber,Beyonce | 1 |
-------------------------------------------------------------------------------------
I tried to split the name column into multiple rows and save it as another table:
WITH TABLE2 AS (
SELECT ID,
NAME
FROM TABLE
UNNEST (SPLIT(NAME)) AS NAME
)
I got:
------------------------
| Name | ID |
------------------------
| Stay | 1 |
------------------------
| Love Yourself | 1 |
------------------------
| Crazy In Love | 1 |
------------------------
I wanted to count the number of users that listen to each single song, but it shows that "grouping by expressions of type STRUCT is not allowed". Can anyone help me with it?
SELECT t2.Name,
COUNT(DISTINCT ID) as num_users
FROM TABLE2 t2
GROUP BY t2.Name.
CodePudding user response:
Consider below
select song, count(distinct id) users
from table, unnest(split(name)) song
group by song