我正在寻找一个关于如何合并两个表而没有任何共同点的SQL答案。
So let's say you have these two tables without anything in common:
Guys Girls
id name id name
--- ------ ---- ------
1 abraham 5 sarah
2 isaak 6 rachel
3 jacob 7 rebeka
8 leah
and you want to merge them side-by-side like this:
Couples
id name id name
--- ------ --- ------
1 abraham 5 sarah
2 isaak 6 rachel
3 jacob 7 rebeka
8 leah
How can this be done?
我正在寻找一个关于如何合并两个表而没有任何共同点的SQL答案。
答案 0 :(得分:13)
您可以通过创建一个键(行号)并加入它来完成此操作。
SQL的大多数方言都支持row_number()
函数。这是一种使用它的方法:
select gu.id, gu.name, gi.id, gi.name
from (select g.*, row_number() over (order by id) as seqnum
from guys g
) gu full outer join
(select g.*, row_number() over (order by id) as seqnum
from girls g
) gi
on gu.seqnum = gi.seqnum;
答案 1 :(得分:2)
假设你想在你的例子中与男孩匹配,并且在记录之间有某种有意义的关系(没有双关语意)......
通常,您可以使用单独的表来表示两者之间的关联(关系)。
这不会为您提供物理表,但它可以让您编写表示最终结果的SQL查询:
SELECT Girls.ID AS GirlId, Girls.Name AS GirlName, Guys.ID AS GuyId, Guys.Name AS GuyName
FROM Couples INNER JOIN
Girls ON Couples.GirlId = Girls.ID INNER JOIN
Guys ON Couples.GuyId = Guys.ID
然后您可以使用Select Into语法
动态创建表格 SELECT Girls.ID AS GirlId, Girls.Name AS GirlName, Guys.ID AS GuyId, Guys.Name AS GuyName
INTO MyNewTable
FROM Couples INNER JOIN
Girls ON Couples.GirlId = Girls.ID INNER JOIN
Guys ON Couples.GuyId = Guys.ID
(但标准规范化规则会说最好将它们保存在不同的表中,而不是创建临时表,除非有性能原因不这样做。)
答案 2 :(得分:2)
仅仅因为我写了它,一个使用CTE的替代方案;
WITH guys2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM guys),
girls2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM girls)
SELECT guys2.id guyid, guys2.name guyname,
girls2.id girlid, girls2.name girlname
FROM guys2 FULL OUTER JOIN girls2 ON guys2.rn = girls2.rn
ORDER BY COALESCE(guys2.rn, girls2.rn);
答案 3 :(得分:-1)
我一直都需要这个, - 使用我的表格输入在Excel中创建模板。这来自一个拥有我的地区的桌子,另一个带有一年的宿舍。结果给出了每个季度/期间的一个区域名称。
SELECT b.quarter_qty,a.mkt_name FROM TBL_MKTS a,TBL_PERIODS b