Otze
Otze

Reputation: 102

SELECT combination of two columns but not sequence

I am growing desperate over this problem: I have a table with just 3 columns, each a reference to an ID of either a member or a journey.

create table sharesRoom (
 member1 int references Members,
 member2 int references Members,
 journey int references Journeys,
 primary key (member1,member2,journey));

I want to write a PLPGSQL function, that raises a notice with the information who has shared a room with whom and how often. For that notice it doesn't matter in what succession the members are stored in the table. So this table

1 2 1
2 1 2
3 4 1
4 3 1
5 6 1
8 7 1

should raise this in a notice: member1 member2 count( how often they shared a room )

1 2 2
3 4 1 (same journey, so this is just 1)
5 6 1
8 7 1

As you see, the order of the member columns doesn't matter.

How is the best way to solve this? I have to admit, I don't even know what to put in the select statement :(

Upvotes: 1

Views: 119

Answers (1)

user533832
user533832

Reputation:

You need a way of filtering out the 'duplicates' where the same members are just in a different order. One way to do this is with greatest and least:

select high_member, low_member, count(*)
from( select distinct greatest(member1, member2) as high_member, 
                      least(member1, member2) as low_member, 
                      journey 
      from sharesRoom )
group by high_member, low_member

Upvotes: 2

Related Questions