简体   繁体   中英

Teradata SQL query to find sum of fields with same column values

I really stuck with one task. I have a table like this

Departure | Arrival    | SUM
 AAA      | ZZZ        | 100
 ZZZ      | AAA        | 50
 AAA      | CCC        | 60

I want get the sum of the same routes and condition here is that I should treat AAA-ZZZ and ZZZ-AAA route as one route. The route ZZZ-AAA it's just route back from the original destination.

I'm trying to obtain the result like this:

Departure | Arrival    | SUM
 AAA      | ZZZ        | 150
 AAA      | CCC        | 60

Any suggestions, ideas please on how can I write my sql query to achieve that ?

Regards, Jack

If you need to preserve to order of columns (ie a,b but no b,a must return the existing combination) you must expand Gordon's solution and add an indicator for the original order.

SELECT
    -- MIN(flag) = 1 -> departure < arrival
    --           = 2 -> arrival > departure or both exist
   CASE WHEN Min(flag)=1 THEN #1 ELSE #2 END AS departure,
   CASE WHEN Min(flag)=2 THEN #1 ELSE #2 END AS arrival,
   Sum(sumcol)
FROM
 (
  SELECT
    Least(Departure, Arrival) AS #1,
    Greatest(Departure, Arrival) AS #2,
    sumcol, -- seems this is already result of an aggregation?
    CASE WHEN departure < arrival THEN 1 ELSE 2 END AS flag
  FROM nodupes  
 ) t
GROUP BY #1,#2;

This could be further simplified without Derived Table, but then it's really hard to understand and it's the same Explain anyway.

Just use least() and greatest() :

select least(Departure, Arrival) as Departure,
       greatest(Departure, Arrival) as Arrival,
       sum(al)
from t
group by least(Departure, Arrival),
         greatest(Departure, Arrival);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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