使用SQL Server在多行中使用相同的ID

时间:2016-10-28 02:10:05

标签: sql-server tsql

我正在制作两个包含列标题ID_1X1Value的表格,如下所示

表1:

ID_1| X1  | Value
A01 | A   | 10 
A01 | B   | 5
A02 | B   | 3
A03 | A   | 4
A02 | A   | 8

表2:

ID_1| X1  | Value
Z01 | A   | 7 
Z01 | B   | 2 
Z01 | C   | 9 
Z03 | A   | 1 
Z02 | B   | 3 
Z03 | B   | 6

我想将这两个表与标题N的附加列组合在一起,如下所示(预期输出):

N  |ID_1| X1  | Value
1  |A01 | A   | 10
1  |A01 | B   | 5
2  |A02 | B   | 3
2  |A02 | A   | 8
3  |A03 | A   | 4
4  |Z01 | A   | 7
4  |Z01 | B   | 2
4  |Z01 | C   | 9
5  |Z02 | B   | 3
6  |Z03 | A   | 1
6  |Z03 | B   | 6

1 个答案:

答案 0 :(得分:3)

我认为您需要union alldense_rank()

select dense_rank() over (order by id_1) as n,
       id_1, x, value
from ((select id_1, x, value from t1
      ) union all
      (select id_1, x, value from t2
      )
     ) t;