问题描述
+----------+----------+--------------+----+
| location | building | buildingcode | id |
+----------+----------+--------------+----+
需要从第二个表2 中插入数据的
:+----------+--------------+
| building | buildingcode |
+----------+--------------+
| B1 | 11 |
| B2 | 11 |
| B3 | 22 |
+----------+--------------+
由于这里的位置是静态的,我在名为@location
的临时变量中具有location的值。
我想将@location
,建筑物,建筑物代码从 table2 插入到 table1 ,但是对于 table1 中的ID列,条件,例如,如果建筑物代码相同,则id值也应该相同。
如果建筑物代码不同,则id值也应该不同。 id的值可以作为id列的最大值,然后递增到1。
因此样本最终输出应如下所示:
+----------+----------+--------------+----+
| location | building | buildingcode | id |
+----------+----------+--------------+----+
| A | B1 | 11 | 1 |
| A | B2 | 11 | 1 |
| A | B3 | 22 | 2 |
+----------+----------+--------------+----+
如何执行插入操作?预先感谢!
解决方法
我认为您应该使用dense_rank()
函数(更多信息here)。
来自MS docs:
此函数返回结果集分区中每一行的排名,排名值中没有空格。特定行的等级为1加上该特定行之前的不同等级值的数量。
以下是示例代码,应该可以使您走上正轨:
declare @table1 table (location char(1),building varchar(50),buildingcode varchar(50),id int)
declare @table2 table (building varchar(50),buildingcode varchar(50))
declare @location char(1)='A'
insert into @table2
values
('B1','11'),('B2',('B3','22')
insert into @table1
select
@location,building,buildingcode,dense_rank() over (order by buildingcode)
from
@table2
select * from @table1
现在table1包含: