SQL并排显示两个结果

时间:2012-10-25 09:02:25

标签: sql sqlite

我有两张桌子,并且正在对每张桌子进行有序选择。我想在一个结果中看到两个订单的结果。

示例(简化):

"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
.
.
.

我想将结果显示为两列,这样我就可以直观地感受到最常见的访客是否也是最佳买家。 (我知道这个例子是糟糕的数据库设计而不是真实场景。这是一个例子)

我想得到这个:

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

我正在使用SQLite。

5 个答案:

答案 0 :(得分:2)

    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

答案 1 :(得分:2)

试试这个

select 
    ISNULL(ts.rn,tv.rn), 
    spent.name, 
    visits.name 
from 
(select *, (select count(*) rn from spent s where s.value>=spent.value ) rn from spent) ts  
    full outer join
(select *, (select count(*) rn from visits v where v.visits>=visits.visits ) rn from visits) tv     
    on ts.rn = tv.rn
order by ISNULL(ts.rn,tv.rn)

它为源表中的每个条目创建一个等级,并在它们的等级上加入两个。如果有重复的排名,他们将在结果中返回重复。

答案 2 :(得分:1)

对于支持公共表表达式和窗口函数的RDBMS(例如,SQL Server,Oracle,PostreSQL),我会使用:

WITH most_visited AS
(
  SELECT ROW_NUMBER() OVER (ORDER BY num_visits) AS num, name, num_visits
  FROM visits
),
most_spent AS
(
  SELECT ROW_NUMBER() OVER (ORDER BY amt_spent) AS num, name, amt_spent
  FROM spent
)
SELECT mv.name, ms.name
FROM most_visited mv INNER JOIN most_spent ms
ON mv.num = ms.num
ORDER BY mv.num

答案 3 :(得分:0)

只需加入table1和table2,其名称为key,如下:

select a.name, 
   b.name, 
   a.NumOfVisitField, 
   b.TotalSpentField 
from table1 a
left join table2 b on a.name = b.name

答案 4 :(得分:0)

我知道这不是一个直接的答案,但我正在寻找它,以防有人需要它:这是一个更简单的解决方案,当每个列只有一个结果时:

select 
   (select roleid from role where rolename='app.roles/anon') roleid, -- the name of the subselect will be the name of the column
   (select userid from users where username='pepe') userid;          -- same here

结果:

                 roleid                |                userid
 --------------------------------------+--------------------------------------
  31aa33c4-4e66-4da3-8525-42689e46e635 | 12ad8c95-fbef-4287-9834-7458a4b250ee