Home > database >  Find names in string and map with value - SQL
Find names in string and map with value - SQL

Time:12-03

I've a data set by list of names:

Sample data

Sample Data

What I'm trying to achieve is: I want to map them into teams

Below are the team views:

Team views

so I want to map them according to the team, and the names are listed such a way that there can be combination of both teams or multiple people from same team.I created a sql query

select name,

( Case 
        when name in ("Tony","Sam", "Ben") then Maverick
        When name in ("Nick",Savi0","Cruz") then Lakers
        else "Bundle"
end) as team_mapping

from people

Please find what my output is and what I'm trying to achieve.

enter image description here

Some additional context: Row 8, 9, 10 are the names of teams which we need to categorise and they are separated by "enter" or "char(10)"

So I want to search names in each row and map based on teams. If 2 people belong to same team then it should there team name and belongs to different then it should show as "bundle".

Here is the trix for ref.

Let me know how I can achieve this and any inputs on this much appreciated. Thanks in advance.

CodePudding user response:

Starting with a table tbl containing all player names. The teams table contains the teams and the player, separated by ,. I changed the names to A1 to A3 for easier readability. The teams table is unnested, so that for each player there is a row.

In the main part, the table tbl is quered and the names are splitted by a new line this is done by:

"""
"""

This is done in a subquery ((Select ... )). Here the splitted and unnested name parts are joined with the team table to obtain the team_name of each player. If there is a team_name missing, because the player is not known, the count(1) differs from the count(team_name) and "unknown player"``is the output. Otherwise and if the max and the min of the team_nameis the same, all players belong to the same team and theteam_nameis the output. Otherwise"Bundled"` is the output.

with tbl as (select * from unnest(["A1","A2","A3","B1","B2","B3","""A1
B1""","""A1
A2""","C"]) name),
teams as (select "team a" team_name, "A1,A2,A3" as players union all select "team b","B1,B2,B3"),
team as (select team_name, player from teams, unnest(split(players,",")) as player)
select *,
((Select if(count(1)!=count(team_name),"unknown player",if(min(team_name)=max(team_name),min(team_name),"Bundle"))
from unnest(split(name,"""
""")) x 
left join team
 on x=player
))
 from tbl
  • Related