[英]sql query group by a particular results as a combination value of two field values
My message table contains two fields, senderid
and recipientid
. 我的消息表包含两个字段,
senderid
和recipientid
senderid
。 I need to list all messages but the combination of values in senderid
and recipientid
don't need to repeat. 我需要列出所有消息,但是
senderid
和recipientid
senderid
中值的组合不需要重复。
For example if senderid = 4
and recipientid = 2
, I need only one combination value of this; 例如,如果
senderid = 4
且recipientid = 2
senderid = 4
recipientid = 2
,则我只需要一个组合值; either it is 4,2 or its is 2,4. 它是4,2还是2,4。
Can any one help me in doing this? 有人可以帮我吗?
Thanks in advance ;) 提前致谢 ;)
select
message,
case when senderid < recipientid then recipientid else senderid end,
case when senderid < recipientid then senderid else recipientid end
from m
group by
message,
case when senderid < recipientid then recipientid else senderid end,
case when senderid < recipientid then senderid else recipientid end
select *
from myTable a
where not exists
(
select top 1 1
from myTable b
where a.senderId = b.receiverId
and a.receiverId = b.senderId
and a.senderId < b.senderId
)
Idea is simple, just make sure the sender/recipient IDs are concatenated in the way such that the smaller IDs is in front of the larger IDs. 想法很简单,只要确保发送者/接收者ID的连接方式使得较小的ID位于较大的ID之前。
select
pair, count(*)
from
(select if(senderid<recipientid, concat(senderid, ',', recipientid), concat(recipientid,',',senderid)) as pair from messages) pairs
group by pair;
Mind the performance of such selection. 注意这种选择的表现。 Maybe you would like to create an additional column to store the pair value when inserting the record, and have the column indexed.
也许您想在插入记录时创建一个额外的列来存储对值,并对该列建立索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.