get the unique routes

Rupa 1 Reputation point
2021-09-28T09:29:55.157+00:00

Hi Team,

find the unique routes

Source:

`135828-s.jpg

output:
135891-d.jpg

Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

3 answers

Sort by: Most helpful
  1. Erland Sommarskog 121.9K Reputation points MVP Volunteer Moderator
    2021-09-28T21:40:41.047+00:00

    Two solutions:

    CREATE TABLE #routes (src char(1), dest char(1))
    go
    INSERT #routes(src, dest)
       VALUES('C', 'H'),
             ('H', 'C'),
             ('K', 'H'),
             ('H', 'K'),
             ('K', 'B')
    go
    SELECT DISTINCT least(src, dest), greatest(src, dest)
    FROM   #routes
    go
    SELECT DISTINCT IIF(src < dest, src, dest), 
                    IIF(src > dest, src, dest)
    FROM   #routes
    

    The one with least and greatest only runs on Azure SQL Database.

    0 comments No comments

  2. MelissaMa-MSFT 24,221 Reputation points
    2021-09-29T01:31:39.163+00:00

    Hi @Rupa ,

    Welcome to Microsoft Q&A!

    Reusing Erland's DDL.

    Please also refer below which has the same output as your expected one:

    select src source,dest destination from (  
    select ROW_NUMBER() over (partition by (IIF(src<dest,src,dest)+IIF(src<dest,dest,src)) order by (select 1)) rn,*   
    from #routes) a where rn=1  
    order by src  
    

    Output:

    source	destination  
    C	H  
    K	H  
    K	B  
    

    Best regards,
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Ronen Ariely 15,206 Reputation points
    2021-09-29T02:30:49.757+00:00

    Same approach using CASE

    SELECT DISTINCT 
        CASE WHEN src < dest THEN src ELSE dest END,
        CASE WHEN src < dest THEN dest ELSE src END
    FROM   #routes
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.