检查具有重复值的列时更新列

时间:2012-05-23 20:56:03

标签: sql sql-server min

我正在使用以下语句选择我的数据:

select distinct min(revision_number) as revno,po_number 
from PO_HEADER 
group by PO_NUMBER
having MIN(revision_number) > 0;

我得到以下数据:

7   30492-SA-EH504
20  30492-PS-SO895
20  30492-RA-DD219
26  30492-SA-KK474
1   30492-BA-AT236
17  30492-RA-DD386
21  30492-PS-FS803
25  30492-PS-WM324
33  30492-SA-NS011

我想在不更改任何其他值的情况下将MIN(REVISION_NUMBER)更新为ZERO。例如,30492-SA-EH504列出修订为:

30492-SA-EH504 7
30492-SA-EH504 8
30492-SA-EH504 9
30492-SA-EH504 10

我只想将当前的最小修订版本(7)更新为零。我尝试了这个更新查询,但它将所有这些更新为零:

update PO_HEADER
set REVISION_NUMBER = '0'
from PO_HEADER
where exists (
select min(revision_number) as revno,po_number 
from PO_HEADER
group by PO_NUMBER
having MIN(revision_number) > 0
);

会选择不同的帮助,或者我需要更复杂的东西。

4 个答案:

答案 0 :(得分:4)

这是另一种解决方法。您实际上可以更新公用表表达式:

with mins as (
  select po_number, revision_number
  from (
  select po_number, revision_number,
    row_number() over (partition by po_number order by revision_number) n
  from Table1
  ) A
  where A.n = 1
)
update mins set revision_number = 0

select * from Table1

<强> SQL Fiddle here.

答案 1 :(得分:1)

有多种方法可以做到这一点。我更喜欢使用“IN”子句的那个:

update PO_HEADER
    set REVISION_NUMBER = '0'
    where (po_header.Revision_NUMBER, po_header.po_number) in 
              (select min(revision_number) as revno, po_number
               from PO_HEADER
               group by PO_NUMBER
               having MIN(revision_number) > 0
              )

您的原始查询在更新表中的行与条件之间没有任何关联。因此,所有评估为true,因为条件为真(行存在)。我认为上面的语法在mysql中工作 - 使用“IN”查找对。如果没有,您可以使用以下内容:

update PO_HEADER
    set REVISION_NUMBER = '0'
    from (select min(revision_number) as revno, po_number
          from PO_HEADER
          group by PO_NUMBER
          having MIN(revision_number) > 0
         ) minr
    where po_header.Revision_NUMBER = minr.Revision_NUMBER and
         po_header.po_number = minr.po_number

答案 2 :(得分:1)

这样的东西
UPDATE poh
  SET poh.RevisionNumber = 0
  FROM POHeader AS poh
  INNER JOIN (select distinct min(revision_number) as revno,po_number 
              from PO_HEADER 
              group by PO_NUMBER
              having MIN(revision_number) > 0) AS poh_rev
  ON poh.PO_Number = poh_rev.PO_Number And poh.RevisionNumber = poh_rev.revno

答案 3 :(得分:1)

Update PO_HEADER
Set revision_number = 0
From (
      select distinct min(revision_number) as revno,po_number  
      from PO_HEADER
      group by PO_NUMBER 
      having MIN(revision_number) > 0
      )Z
Where PO_HEADER.revision_number = Z.revno
  and PO_HEADER.po_number = Z.po_number