30

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

但是我如何加入行号?

如果我没有 order-by,但只想按它们出来的顺序排列行怎么办?

RowA Row4
RowB Row3
RowC Row2
RowD Row1

就像在加入

SELECT val
FROM A

SELECT val
FROM B
4

2 回答 2

46

试试这个:

在 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小提琴演示

于 2012-10-19T10:29:35.793 回答
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
于 2018-10-15T16:02:24.980 回答