-- Create the table
CREATE TABLE emp_details (
    emp_name VARCHAR(10),
    city VARCHAR(15)
);

-- Insert sample data
INSERT INTO emp_details (emp_name, city) VALUES
('Sam', 'New York'),
('David', 'New York'),
('Peter', 'New York'),
('Chris', 'New York'),
('John', 'New York'),
('Steve', 'San Francisco'),
('Rachel', 'San Francisco'),
('Robert', 'Los Angeles');

with emp2 as (
select *, row_number() over(partition by city order by city) as row_num 
    from emp_details
)
, trans_ct as (
select 
    e1.city, e1.emp_name, e1.row_num, case when e1.row_num%3=0 then 3 else e1.row_num%3 end as mod_num, 
    (e1.row_num - case when e1.row_num%3=0 then 3 else e1.row_num%3 end) as mod_num_dif
    from emp2 e1
)
,team_group as (
select city, GROUP_CONCAT(emp_name ORDER BY emp_name ASC SEPARATOR ', ') as team_grp
    from trans_ct
group by city, mod_num_dif
)
select city, team_grp, concat('Team_',row_number() over(order by city asc)) as team_name
    from team_group
;

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: