MySQL自我加入的独特组合

时间:2018-07-13 09:22:11

标签: mysql

我有一个如下表的会话:

sessionid   conversationid  agentid

SES153130074572578571   001a60f3-d95c-4434-a8c0-fabb7d815277_OD112807172056802000   igs.399760
SES15313020119321989    001a60f3-d95c-4434-a8c0-fabb7d815277_OD112807172056802000   hgs.20073
SES153130276854998136   001a60f3-d95c-4434-a8c0-fabb7d815277_OD112807172056802000   igs.100000000308235
SES153128080803552749   00803e49-0325-4bef-b133-8c5e97f2fccc_OD112706138643350000   hgs.20031
SES153128342589414965   00803e49-0325-4bef-b133-8c5e97f2fccc_OD112706138643350000   hgs.20031
SES153129466185930775   008bba3a-98fa-414a-8f99-96956513bc66_OD112757403158502000   igs.401836
SES153129612178429544   008bba3a-98fa-414a-8f99-96956513bc66_OD112757403158502000   hgs.20076
SES153129179161527928   00976601-aac7-4ec7-9e03-61cd59875650_Payment Related Queries    hgs.20071
SES153129238786010778   00976601-aac7-4ec7-9e03-61cd59875650_Payment Related Queries    igs.100000000307102

我希望仅将一个会话ID分配给一个座席ID的行(如果将一个会话ID分配给多个座席ID的情况将被省略)     即我的输出应如下所示:

sessionid   conversationid  agentid
SES153128080803552749   00803e49-0325-4bef-b133-8c5e97f2fccc_OD112706138643350000   hgs.20031
SES153128342589414965   00803e49-0325-4bef-b133-8c5e97f2fccc_OD112706138643350000   hgs.20031

请提供有关查询的帮助

2 个答案:

答案 0 :(得分:0)

select sessionid,agentid,conversationid from session as S
inner join 
(
select agentid from session
group by agentid
having count(*)=1
) T
on S.agentid=T.agentid 

答案 1 :(得分:0)

尝试以下操作:

select s.sessionid, s.agentid, s.conversationid 
from session s
inner join 
(
  select conversationid 
  from session
  group by conversationid
  having count(distinct agentid) = 1
) uq
on s.conversationid = uq.conversationid 

uq将包含所有conversationid,其中不同代理的数量为1。Join用原始数据来获取conversationid的所有行。