Home > Net >  Map distinct pairs using join
Map distinct pairs using join

Time:02-23

I have these 2 tables which I would like to query:

create table active_pairs
(
    pair                  text,
    exchange_id           integer
);


create table exchanges
(                        
    exchange_id         integer
);

INSERT INTO active_pairs (pair, exchange_id)

VALUES ('London/Berlin', 2),
       ('London/Berlin', 3),
       ('Paris/Berlin', 4),
       ('Paris/Berlin', 3),
       ('Oslo/Berlin', 2),
       ('Oslo/Berlin', 6),
       ('Huston/Berlin', 2);
       
INSERT INTO exchanges (exchange_id)

VALUES (2),
       (3),
       (4),
       (3),
       (2),
       (6),
       (2);  

 

I tried to use this SQL query to get records with single unique record for pair column:

SELECT * 
   FROM active_pairs ap 
   INNER JOIN exchanges ce on ap.exchange_id = ce.exchange_id 
   WHERE ap.exchange_id = :exchangeId 
GROUP BY pair, ap.exchange_id, ce.exchange_id
HAVING COUNT(ap.pair) = 1 
ORDER BY :sort 
LIMIT :limit 
OFFSET :offset

The problem is that I need first to query for distinct pairs and after that map them for exchange_id. Into the above solution I might have pairs with a single record but for several exchanges. I need unique pair.

Can you advise me how I can fix this?

CodePudding user response:

Use array_agg() for adding multiple exchange_id with unique pair. Use distinct keyword inside array_agg() for removing duplicate exchange_id. When passing specific input then enable WHERE clause otherwise disable it. If single exchange_id then comment exchange_id column in select clause.

-- PostgreSQL
select ap.pair
     , array_to_string(array_agg(distinct ap.exchange_id), ',') exchange_id
from active_pairs ap
inner join exchanges e
        on ap.exchange_id = e.exchange_id
       -- and ap.exchange_id = 2 
group by ap.pair

Please check this url https://dbfiddle.uk/?rdbms=postgres_11&fiddle=68dd8fb546e3c49a9821605dd495dfd8

  • Related