简体   繁体   中英

How to compare pairs of values in column of SQL, for all possible pairs?

If anyone could help on this, it would be great! I work with version 9.3 of postgreSQL .

I have one table (called likes ) with three columns;

  • trackurl
  • userurl
  • date

That is full of data, and another (now empty) table (called track2tracks ) with 4 columns ;

  • track1
  • track2
  • date
  • userurl

The key for table 'likes' is (trackurl, userurl, date) . The key for table track2tracks is (track1, track2, date, userurl)

I would like to fill the table track2tracks with all the combinations of tracks that are liked by the same user, showing the latest date of the two likes.

So far I understand that: I need to partition the like-table on userurl, and then for each user compare all the pairs of likes on their date. Then I need to add these pairs (as track1 and track2) to the track2tracks-table, also adding the latest date and the corresponding user.

The biggest problem I have is how to compare values of pairs (of the same column; date).

Thank you very much in advance!!

INSERT INTO track2tracks
  SELECT l1.trackurl, l2.trackurl, max(greatest(l1.date, l2.date)), l1.userurl
  FROM likes l1
  JOIN likes l2 ON (l1.userurl = l2.userurl) AND (l1.trackurl != l2.trackurl)
  GROUP BY l1.trackurl, l2.trackurl, l1.userurl;

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