https://youtube.com/watch?v=ka9kDqkITX4&list=PLavw5C92dz9Hxz0YhttDniNgKejQlPoAn&index=15

DROP TABLE IF EXISTS Friends;

CREATE TABLE Friends
(
	Friend1 	VARCHAR(10),
	Friend2 	VARCHAR(10)
);
INSERT INTO Friends VALUES ('Jason','Mary');
INSERT INTO Friends VALUES ('Mike','Mary');
INSERT INTO Friends VALUES ('Mike','Jason');
INSERT INTO Friends VALUES ('Susan','Jason');
INSERT INTO Friends VALUES ('John','Mary');
INSERT INTO Friends VALUES ('Susan','Mary');

select * from Friends;

Pasted image 20241118203618.png

WITH
UNION_UNION ALL

WITH All_Friends AS (
select Friend1,Friend2 from Friends
UNION 
SELECT Friend2,Friend1 FROM friends
)
SELECT f.friend1,f.friend2, COUNT(af.friend2) OVER (PARTITION BY f.friend1,f.friend2 ORDER BY f.friend1,f.friend2 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS MUTUAL_FRIENDS
FROM friends f
LEFT JOIN All_friends af
ON f.friend1 = af.friend1 AND af.friend2 IN (SELECT af2.friend2 FROM all_friends af2 WHERE af2.friend1 = f.friend2)