表1
START END rownum
1 1 1
2 3 2
4 7 3
8 8 4
9 9 5
表2
START END rownum
1 1 1
2 3 2
4 7 3
8 8 4
9 9 5
查询:
SELECT TB1.START,TB1.[END],TB1.rownum as row_1,TB2.START,TB2.[END],TB2.rownum as row_2 FROM
(
select START,[END],ROW_NUMBER() over(order by import_num) as rownum from
table1
) TB1
INNER JOIN
(
select START,[END],ROW_NUMBER() over(order by import_num) as rownum from
table1
) TB2
ON TB1.rownum + 1 = TB2.rownum
结果:
START END row_1 START END row_2
1 1 1 2 3 2
2 3 2 4 7 3
4 7 3 8 8 4
8 8 4 9 9 5
问题:
当我的连接条件在tb1.rownum + 1时,为什么rownum会指示-1,2,3,4? 不应该是2,3,4,5
答案 0 :(得分:1)
你的输出对我来说似乎很好。我不知道展示这个的最佳方式,但这里有一种方法可视化什么是加入什么:
Table1.RowNum +1 Table2.RowNum
1 2 2
2 3 3
3 4 4
4 5 5
5 6 null /* no 6 in Table2.RowNum */
null null 1 /* no 0 in Table1.RowNum */
在这里的最后两行中,看看Table2.RowNum中没有6?此外,您不能将1添加到任何Table1.RowNum并匹配Table2.RowNum = 1
另外,我不确定查询中import_num
的来源,因为您没有在表定义中向我们展示。{1}}。这在我看来是一个混乱的潜在根源。
答案 1 :(得分:0)
尝试将此行添加1到rownum而row_number,这将加入2,3,4,5。
SELECT TB1.START,TB1.[END],TB1.rownum as row_1,TB2.START,TB2.[END],TB2.rownum as row_2 FROM
(
select START,[END],ROW_NUMBER() over(order by import_num) + 1 as rownum from
table1
) TB1
INNER JOIN
(
select START,[END],ROW_NUMBER() over(order by import_num) as rownum from
table1
) TB2
ON TB1.rownum = TB2.rownum
答案 2 :(得分:0)
你JOIN
使用rownum + 1,但不是SELECT
它......
更改:
SELECT TB1.START,TB1.[END],TB1.rownum as row_1
,TB2.START,TB2.[END],TB2.rownum as row_2 FROM ....
要:
SELECT TB1.START,TB1.[END],(TB1.rownum + 1) as row_1
,TB2.START,TB2.[END],TB2.rownum as row_2 FROM ....