2012-01-24 11 views
0

다음 쿼리에 대한 도움이 필요합니다.동일한 테이블의 필드를 기반으로 oldID 필드를 업데이트하십시오.

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)를 가리켜 야합니다.

실제 테이블에는 사용할 수있는 날짜 입력란이 있지만 지금은 도움이 될 것입니다. 해당 고객의 ID가 최소 ID가 아닌 경우 다음 OldIDID 값으로 설정되어 Data CTE는 기본적으로 그냥 각 고객의 최소 ID을 결정

;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 

, 그리고 :

+0

한 준비. – danihp

답변

0

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

두 답변이 모두 작동합니다.이 중 하나가 더 명확합니다. –

1

CTE를 사용하여이 시도 . 여러 행 만 고객을 업데이트, CTE와

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 
관련 문제