根据同一个表中的字段更新oldID字段

时间:2012-01-24 21:49:52

标签: sql sql-server-2005 join

我需要以下查询的帮助。

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)。
  3. 虽然在我的实际表中,我有一堆日期字段,我可能会使用,但这对我现在有帮助。

2 个答案:

答案 0 :(得分:1)

使用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

答案 1 :(得分:0)

使用cte,没有subquerys,只更新多行客户:

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