如何在sql server中对行号进行内连接

时间:2012-10-19 10:27:09

标签: sql sql-server sql-server-2008

SQL Server 2008

两张桌子:

表A有以下数据:

RowA
RowB
RowC
RowD

表B有以下数据:

Row4
Row3
Row2
Row1

我想获得以下输出:

RowA Row1
RowB Row2
RowC Row3
RowD Row4

两个表之间唯一的共同值是行号

我当然可以单独获取数据:

SELECT val
FROM A
ORDER BY val

SELECT val
FROM B
ORDER BY val

但我如何加入行号?

如果我没有订单,但只想按行出的顺序排序,该怎么办?

RowA Row4
RowB Row3
RowC Row2
RowD Row1

的连接中
SELECT val
FROM A

SELECT val
FROM B

2 个答案:

答案 0 :(得分:26)

试试这个:

在sql server 2008中使用ROW_NUMBER()函数

select A.val,B.val 
from(
    SELECT val,row_number() over (order by val) as row_num
    FROM A)A
join
    (SELECT val,row_number() over (order by val) as row_num
    FROM B)B
on  A.row_num=B.row_num
ORDER BY A.val,B.val


SQL fiddle demo

答案 1 :(得分:0)

select A.sectionname, A.Basicprice,A.Brand,A.Description,A.Description,A.Grandtotal,A.GST,A.Gstvalue,A.Hsncode,A.Image,A.Installationcharge,A.Model,B.Age,B.Mark,B.Name,B.class

from(
   SELECT Class,row_number() over (order by class) as row_num,Age,Mark,Name
   FROM classtable)B
   LEFT join
   (SELECT sectionname,row_number() over (order by sectionname) as row_num,Basicprice,Brand,Description,Grandtotal,GST,Gstvalue,Hsncode,Image,Installationcharge,Model
   FROM testtable)A

on  A.row_num=B.row_num