0

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

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)不更改任何其他值的情况下将其更新为零。例如,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

4 回答 4

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 小提琴在这里。

于 2012-05-23T21:05:17.203 回答
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
              )

您的原始查询在更新表中的行与条件之间没有任何联系。因此,所有评估为真,因为条件为真(存在行)。我认为上述语法在 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
于 2012-05-23T21:03:44.943 回答
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
于 2012-05-23T21:11:42.340 回答
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
于 2012-05-24T04:53:14.170 回答