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

SQL insert same value in a column based on if another column has same values

我有一个 table 叫 table1:

+----------+----------+--------------+----+
| location | building | buildingcode | id |
+----------+----------+--------------+----+

需要从第二个 table2:

插入数据
+----------+--------------+
| building | buildingcode |
+----------+--------------+
| B1       |           11 |
| B2       |           11 |
| B3       |           22 |
+----------+--------------+

因为位置在这里是静态的,我在一个名为 @location.

的临时变量中有位置的值

我想插入@location,建筑,建筑代码从table2table1,但是对于 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 文档:

This function returns the rank of each row within a result set partition, with no gaps in the ranking values. The rank of a specific row is one plus the number of distinct rank values that come before that specific row.

这是一个示例代码,应该会让您走上正轨:

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

现在表 1 包含: