SQL Server>复制某些行并更改2个值

时间:2012-05-31 07:32:09

标签: sql-server tsql

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

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(revno)复制该行,并将其revno设置为ZERO。我已尝试插入使用整个表并使用上面的where exists和我的select语句,它会复制整个表格。

这就是30492-SA-EH504当前的表格:

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

以下是我希望它照顾的方式:

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

我正在浏览MSDN for T-SQL以找出在这种情况下如何使用exists,但正如我所说,它要么复制一切,要么就像我目前未能做到的那样。

2 个答案:

答案 0 :(得分:1)

insert into PO_HEADER(po_number, revision_number, ....other columns)
    select POH.po_number, 0, ...other columns
    from PO_Header AS POH
    INNER JOIN (select po_number, MIN(revision_number) as min_revision_number
        from PO_HEADER 
        group by PO_NUMBER
        having MIN(revision_number) > 0) AS POHMin ON POHMin.po_number = POH.po_number
            AND POHMin.min_revision_number = POH.revision_number

答案 1 :(得分:1)

这应该按预期工作:

WITH CTE AS(
    SELECT RevNum = ROW_NUMBER()OVER(PARTITION BY po_number ORDER BY revision_number)
         , revision_number
         , po_number
    FROM PO_HEADER t
) 
INSERT INTO PO_HEADER 
SELECT 0, t1.po_number
FROM CTE t1
WHERE t1.RevNum = 1
AND EXISTS(
    SELECT  NULL FROM CTE t2
    WHERE   t2.po_number = t1.po_number
    AND     t2.RevNum > 1
)