0

表格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吗

4

3 回答 3

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您查询中的来源,因为您没有在表定义中向我们展示。这在我看来是一个潜在的混乱来源。

于 2013-05-06T16:50:53.123 回答
0

尝试在 row_number 时将 1 添加到 rownum,这将加入 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 
于 2013-05-06T16:55:58.610 回答
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 ....
于 2013-05-06T17:03:14.520 回答