【问题标题】:SQL insert same value in a column based on if another column has same valuesSQL根据另一列是否具有相同的值在列中插入相同的值
【发布时间】:2020-09-02 18:20:24
【问题描述】:

我有一张名为 table1 的表格:

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

需要从第二个table2向其中插入数据:

+----------+--------------+
| building | buildingcode |
+----------+--------------+
| B1       |           11 |
| B2       |           11 |
| B3       |           22 |
+----------+--------------+

因为这里的位置是静态的,所以我在一个名为 @location 的临时变量中拥有位置值。

我想插入@location, building, buildingcode 从 table2table1,但是对于 table1 中的 id 列有一个条件就像如果建筑代码相同,那么 id 值也应该相同。

如果建筑代码不同,则 id 值也应该不同。 id的值可以作为id列的最大值,然后递增到1。

所以样本最终输出应该是这样的:

+----------+----------+--------------+----+
| location | building | buildingcode | id |
+----------+----------+--------------+----+
| A        | B1       |           11 |  1 |
| A        | B2       |           11 |  1 |
| A        | B3       |           22 |  2 |
+----------+----------+--------------+----+

如何进行这个插入操作?提前致谢!

【问题讨论】:

  • 您能否向我们展示这两个表的示例数据以及结果。
  • 我只有一张表,其中包含字段 building--buildingcode。仅从该表中,需要插入另一个具有字段位置--建筑--建筑代码--id 的表。该输出表已给出。

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


【解决方案1】:

我认为你应该使用dense_rank() 函数(更多信息here)。

来自 MS 文档:

此函数返回结果集分区中每一行的排名,排名值没有间隙。特定行的排名是该特定行之前的不同排名值的数量的一加。

下面是一个示例代码,应该会让你走上正轨:

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 包含:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2022-08-03
    • 1970-01-01
    • 2017-02-14
    相关资源
    最近更新 更多