【问题标题】:update oldID field based on fields in the same table根据同一张表中的字段更新 oldID 字段
【发布时间】:2012-02-18 03:58:00
【问题描述】:

我需要有关以下查询的帮助。

create table #table1
(id int not null primary key identity,
customer_name varchar(25),
usage float,
oldID int null
)


insert into #table1 values('ABC',46.5,null)
insert into #table1 values('ABC',46.5,null)
insert into #table1 values('DEF',36.8,null)
insert into #table1 values('XYZ',50.1,null)
insert into #table1 values('DEF',36.8,null)
insert into #table1 values('XYZ',50.1,null)

select * from #table1

我希望我的表像这样更新

id          customer_name             usage                  oldID
----------- ------------------------- ---------------------- -----------
1           ABC                       46.5                   NULL
2           ABC                       46.5                   1
3           DEF                       36.8                   NULL
4           XYZ                       50.1                   NULL
5           DEF                       36.8                   3
6           XYZ                       50.1                   4
  1. 两个记录名称和用法相同,表示更新后的记录。
  2. 在新记录中,oldID 字段应指向其旧记录 (ID)。

虽然在我的实际表格中,我有一堆我可能可以使用的日期字段,但这对我现在有帮助。

【问题讨论】:

  • +1 表示准备测试的样本数据。

标签: sql sql-server-2005 join


【解决方案1】:

使用 cte,没有子查询,只更新多行的客户:

with cte as (
   select customer_name, min( id ) as id
   from #table1
   group by customer_name
   having count(*) > 1
)
update #table1 
 set oldID = cte.id
 from cte 
 where #table1.customer_name = cte.customer_name
 and #table1.id != cte.id 

【讨论】:

    【解决方案2】:

    使用 CTE 试试这个:

    ;WITH data AS
    (
        SELECT 
            id, customer_name,
            OldID = (SELECT MIN(id) FROM #table1 t2 WHERE t2.customer_name = t.customer_name)
        FROM #table1 t
    )
    UPDATE #table1
    SET OldID = data.OldID
    FROM Data
    WHERE 
        data.customer_Name = #table1.customer_name
        AND #table1.ID <> data.oldid
    
    select * from #table1
    

    Data CTE 基本上只是确定每个客户的最小 ID,如果该客户的 ID 不是该最小 ID,则 OldID 设置为该 ID 值。

    当我运行它时,我得到一个结果输出:

    id  customer_name   usage   oldID
     1   ABC            46.5    NULL
     2   ABC            46.5    1
     3   DEF            36.8    NULL
     4   XYZ            50.1    NULL
     5   DEF            36.8    3
     6   XYZ            50.1    4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多