简体   繁体   English

SQL查询选择值的唯一组合,两列顺序被忽略

[英]SQL query to select unique combinations of values, with two columns order being ignored

I am trying to build a SQL query where unique rows are selected based on specific criteria, but I am at a loss on how to construct it. 我正在尝试构建一个SQL查询,其中根据特定条件选择了唯一的行,但是我对如何构造它感到茫然。

The rows have a varchar Conversation ID, varchar sender, and varchar recipient. 这些行具有varchar会话ID, varchar发送方和varchar接收方。

I need the results to be all distinct combinations of the Conversation ID and sender and recipient, but repeats of senders in the recipient column or vice versa are treated as treated as being the same. 我需要结果是“对话ID”与发件人和收件人的所有不同组合,但是将“收件人”列中发件人的重复,反之亦然,都应视为相同。

For example: 例如:

ID      ,Sender      ,Recip
-------------------------
Convo1  ,PersonA     ,PersonB
Convo1  ,PersonB     ,PersonA
Convo1  ,PersonC     ,PersonA
Convo1  ,PersonC     ,PersonA
Convo1  ,PersonA     ,PersonC
Convo1  ,PersonC     ,PersonA
Convo2  ,PersonB     ,PersonD
Convo2  ,PersonB     ,PersonA

A query that would return: 查询将返回:

Convo1, PersonA, PersonB
Convo1, PersonC, PersonA
Convo2, PersonB, PersonD
Convo2, PersonB, PersonA

In standard SQL, you would do this using the case statement: 在标准SQL中,您可以使用case语句执行此操作:

select id, (case when sender < recip then sender else recip end) as person1,
       (case when sender < recip then recip else sender end) as person2
from conversations
group by id,
         (case when sender < recip then sender else recip end),
         (case when sender < recip then recip else sender end);

Many databases support the least() and greatest() functions which simplify the code: 许多数据库都支持least()greatest()函数,可简化代码:

select id, least(sender, recip) as person1, greatest(sender, recip) as person2
from conversations
group by id, least(sender, recip) as person1, greatest(sender, recip);

One option is to order the conversation in some way. 一种选择是以某种方式订购对话。 Since your sender and recipient are varchar s, alphabetically would seem the be the most straightforward: 由于您的发送者和接收者都是varchar ,因此按字母顺序似乎是最简单的:

SELECT DISTINCT
    ID, 
    CASE WHEN Sender <= Recip
        THEN Sender
        ELSE Recip
        AS Person1,
    CASE WHEN Sender <= Recip
        THEN Recip
        ELSE Sender
        AS Person2
FROM Conversations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM