从两个没有联接条件的表中选择数据,t-sql
如果有人能帮忙,我将不胜感激。 我有两个没有关系的表: 表1从两个没有联接条件的表中选择数据,t-sql,sql,sql-server,tsql,Sql,Sql Server,Tsql,如果有人能帮忙,我将不胜感激。 我有两个没有关系的表: 表1 ID NAME VALUE 1 abc 10 2 def 20 3 def 20 表2 ID2 NAME2 VALUE2 5 ghi 30 6 gkl 40 我想要一个select语句,它将显示两个表中的数据,如下所示: ID NAME VALUE ID2 NAME2 VALUE
ID NAME VALUE
1 abc 10
2 def 20
3 def 20
表2
ID2 NAME2 VALUE2
5 ghi 30
6 gkl 40
我想要一个select语句,它将显示两个表中的数据,如下所示:
ID NAME VALUE ID2 NAME2 VALUE2
1 abc 10 5 ghi 30
2 def 20 6 gkl 40
3 def 20
要点是在一行中显示每条记录的数据,该表可以如下所示:
ID NAME VALUE ID2 NAME2 VALUE2
5 ghi 30
6 gkl 40
如果表1
没有记录。对于表2
,情况也是如此。
我尝试使用交叉连接,但数据将重复
非常感谢您需要添加一个
加入
条件。在这种情况下,使用行号()
在每一侧添加一个序列号。然后完全外部联接
以获取所有记录:
select t1.id, t1.name, t1.value, t2.id as id2, t2.name as name2, t2.value as value2
from (select t1.*, row_number() over (order by id) as seqnum
from table_1 t1
) t1 full outer join
(select t2.*, row_number() over (order by id) as seqnum
from table_2 t2
) t2
on t1.seqnum = t2.seqnum;
试试这个:
with Table_1(ID, NAME, VALUE) as (
select 1, 'abc', 10 union all
select 2, 'def', 20 union all
select 3, 'def', 20
), Table_2(ID2, NAME2, VALUE2) as (
select 5, 'ghi', 30 union all
select 6, 'gkl', 40
), prep_table_1 (ID, NAME, VALUE, rn) as (
select id, name, value, row_number() over(order by id)
from table_1
), prep_table_2 (ID2, NAME2, VALUE2, rn) as (
select id2, name2, value2, row_number() over(order by id2)
from table_2
)
select t1.ID, t1.NAME, t1.VALUE, t2.ID2, t2.NAME2, t2.VALUE2
from prep_table_1 t1
full outer join prep_table_2 t2 on t1.rn = t2.rn
这同样有效
从表1、表2中选择*表1中的行与表2中的行之间是否存在任何关系?我的意思是如何确定ID为1的行应该与您示例中ID为5的行相邻?仅通过row_number()表_2表没有ID列,而是id2列这是交叉连接。