簡體   English   中英

sql查詢組按特定結果作為兩個字段值的組合值

[英]sql query group by a particular results as a combination value of two field values

我的消息表包含兩個字段, senderidrecipientid senderid 我需要列出所有消息,但是senderidrecipientid senderid中值的組合不需要重復。

例如,如果senderid = 4recipientid = 2 senderid = 4 recipientid = 2 ,則我只需要一個組合值; 它是4,2還是2,4。

有人可以幫我嗎?

提前致謝 ;)

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
)

想法很簡單,只要確保發送者/接收者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;

注意這種選擇的表現。 也許您想在插入記錄時創建一個額外的列來存儲對值,並對該列建立索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM