• durga.palepu (6/13/2016)


    Thanks, that's awesome solution.

    Your approach to provide hints so that I would work on actual solution is excellent so that I could learn my self.

    Here follow's my solution implementations:

    using GROUP BY:

    SELECT

    CASE WHEN c_From < c_To then c_From else c_To end as c_from

    ,CASE WHEN c_to > c_From then c_to else c_from end as c_to

    ,c_Distance

    FROM #logistics

    GROUP BY CASE WHEN c_From < c_to then c_from else c_to end

    , CASE WHEN c_to > c_from then c_to else c_from end

    , c_distance;

    using ROW_NUMBER():

    with ctelogistics

    as

    (

    select c_from,c_to,c_Distance, ROW_NUMBER() over(partition by CASE WHEN c_From < c_To then c_From else c_To end

    ,CASE WHEN c_to > c_From then c_to else c_from end order by c_from) as rn

    from #logistics

    )

    select c_From,c_to,c_Distance

    from ctelogistics

    where rn=1;

    Another way:

    SELECT [From], [To], Distance

    FROM

    (

    SELECT

    [From] = CASE WHEN [From] < [To] THEN [From] ELSE [To] END,

    [To] = CASE WHEN [To] > [From] THEN [To] ELSE [From] END,

    Distance

    FROM #Logistics

    ) x

    GROUP BY [From], [To], Distance;

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001