你可以这样考虑:
元数据创建:
Create table acc_table(name varchar(20), account_id int);
Insert into acc_table values('John',123);
Insert into acc_table values('Lisa',123);
Insert into acc_table values('Tiger',567);
Insert into acc_table values('Lisa',567);
Insert into acc_table values('Lisa',890);
Insert into acc_table values('Tiger',890);
Insert into acc_table values('max',111);
Insert into acc_table values('lucy',222);
Insert into acc_table values('monica',222);
Insert into acc_table values('Jenifer',222);
Insert into acc_table values('lucy',333);
Insert into acc_table values('monica',333);
Insert into acc_table values('Jenifer',333);
Insert into acc_table values('lucy',444);
Insert into acc_table values('monica',444);
Insert into acc_table values('Jenifer',444);
下面的查询将产生如图所示的结果
With BaseData (members,account_id) as
(
Select group_concat(name) members, Account_id
from
(Select *, row_number() over ( partition by account_id order by name ) rnum
from acc_table) a
group by account_id
order by rnum
)
select members, count(account_id) Count_of_Shared_Accounts
from BaseData
group by members;
结果:
members | Count_of_Shared_Accounts
:------------------ | -----------------------:
max | 1
John,Lisa | 1
Jenifer,lucy,monica | 3
Lisa,Tiger | 2
由于 MySql 不支持 PIVOT 功能,因此很难使用列数是动态的变通方法进行透视(此处相同,因为我们不知道有多少成员可以共享一个帐户)。
可以在here找到动态将 CSV 字符串拆分为列的详细信息(如最终的预期输出)。