/*
Paypal SQL Interview Question
Write a SQL query to determine the number of unique two-way money transfer relationships,
where a two-way relationship is established if a user has sent money to another user and also received money from the same user.
*/
-- Schema Setup
CREATE TABLE payments (
payer_id INT,
recipient_id INT,
amount INT
);
INSERT INTO payments (payer_id, recipient_id, amount) VALUES
(1, 2, 100),
(2, 1, 150),
(3, 4, 200),
(4, 3, 250),
(5, 6, 300),
(6, 5, 350),
(1, 3, 400),
(3, 1, 450),
(2, 4, 500);
-- Solution
SELECT
COUNT(DISTINCT LEAST(p1.payer_id, p1.recipient_id), GREATEST(p1.payer_id, p1.recipient_id)) AS unique_relationships
FROM payments p1
JOIN payments p2
ON p1.payer_id = p2.recipient_id
AND p1.recipient_id = p2.payer_id;
To embed this program on your website, copy the following code and paste it into your website's HTML: