Skip to content
Advertisement

SQL: CROSS JOIN over table partitions

I have the following table

session_id | page_viewed
    1      |     A
    1      |     B
    1      |     C
    2      |     B
    2      |     E

What I would like to do is a cross join of the page_viewed column with itself but where the cross join is done on the partitions from session_id. So, from the table above the query would return:

session_id | page_1 | page_2
    1      |    A   |   A
    1      |    A   |   B
    1      |    A   |   C
    1      |    B   |   A
    1      |    B   |   B
    1      |    B   |   C
    1      |    C   |   A
    1      |    C   |   B
    1      |    C   |   C
    2      |    B   |   B
    2      |    B   |   E
    2      |    E   |   B
    2      |    E   |   E

I have looked into window functions today trying to find a way around it but it seems join functions cannot be used. Can anyone help?

Advertisement

Answer

You may join giving only the session_id as the join criteria:

SELECT
    t1.session_id,
    t1.page_viewed AS page_1,
    t2.page_viewed AS page_2
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.session_id = t2.session_id;
-- ORDER BY clause optional, if you need it here

enter image description here

Demo

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement