Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL display two results side-by-side

Tags:

sql

sqlite

I have two tables, and am doing an ordered select on each of them. I wold like to see the results of both orders in one result.

Example (simplified):

"SELECT * FROM table1 ORDER BY visits;"
name|# of visits
----+-----------
 AA | 5
 BB | 9
 CC | 12
.
.
.

"SELECT * FROM table2 ORDER BY spent;"
name|$ spent
----+-------
 AA | 20
 CC | 30
 BB | 50
.
.
.

I want to display the results as two columns so I can visually get a feeling if the most frequent visitors are also the best buyers. (I know this example is bad DB design and not a real scenario. It is an example)

I want to get this:

name by visits|name by spent
--------------+-------------
 AA           | AA
 BB           | CC
 CC           | BB

I am using SQLite.

like image 692
Baruch Avatar asked Feb 19 '23 17:02

Baruch


1 Answers

    Select A.Name as NameByVisits, B.Name as NameBySpent
    From (Select C.*, RowId as RowNumber From (Select Name From Table1 Order by visits) C) A
    Inner Join
    (Select D.*, RowId as RowNumber From (Select Name From Table2 Order by spent) D) B
    On A.RowNumber = B.RowNumber
like image 124
xray1986 Avatar answered Feb 25 '23 10:02

xray1986