SQL根据另一列是否具有相同的值在列中插入相同的值

时间:2020-09-02 18:20:24

标签: sql sql-server tsql sql-server-2017

我有一个名为 table1 的表:

+----------+----------+--------------+----+
| 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 |
+----------+----------+--------------+----+

如何执行插入操作?预先感谢!

1 个答案:

答案 0 :(得分:0)

我认为您应该使用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','11')
,('B3','22')

insert into @table1
select 
     @location
    , building
    , buildingcode
    , dense_rank() over (order by buildingcode) 
from 
    @table2

select * from @table1

现在table1包含:

enter image description here