1

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

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为零。我尝试使用整个表插入并使用上面where existsselect语句,它会复制整个表。

这是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

我正在浏览 T-SQL 的 MSDN 以了解在这种情况下如何使用存在,但正如我所说的那样,它要么复制所有内容,要么什么都不复制,而我目前没有这样做。

4

2 回答 2

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
于 2012-05-31T07:37:17.943 回答
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
)
于 2012-05-31T07:50:01.570 回答