每件商品的前3条记录

时间:2014-06-09 21:19:56

标签: sql sql-server

我们有一个存储过程,逐行浏览选定的库存商品,并使用每个库存商品的3个最新销售订单编号填充表格:

INSERT  INTO TOP3_STOCK_SALES_DATA
        ( ORDERDATE ,
          SEQNO ,
          STOCKCODE ,
          QUANTITY ,
          ROW
        )
        SELECT TOP 3
                h.ORDERDATE ,
                h.SEQNO ,
                l.STOCKCODE ,
                l.ORD_QUANT ,
                ROW_NUMBER() OVER ( ORDER BY h.ORDERDATE DESC, h.SEQNO DESC ) AS row
        FROM    SALESORD_HDR h ,
                SALESORD_LINES l
        WHERE   l.HDR_SEQNO = h.SEQNO
                AND l.STOCKCODE IN ( '1000-ACQ45' )
        ORDER BY h.ORDERDATE DESC ,
                h.SEQNO DESC

有没有办法批量运行此语句(或获得相同的结果),而不是逐行运行?

1 个答案:

答案 0 :(得分:1)

您的书面查询不会返回每个库存项目的TOP 3,但它将仅返回返回结果集中的TOP 3记录。要获得每个库存项目的TOP 3,请参见下文。

INSERT  INTO TOP3_STOCK_SALES_DATA
        ( ORDERDATE ,
          SEQNO ,
          STOCKCODE ,
          QUANTITY ,
          ROW
        )
SELECT   A.ORDERDATE 
        ,A.SEQNO 
        ,A.STOCKCODE 
        ,A.ORD_QUANT
        ,A.row 
FROM (
        SELECT 
                h.ORDERDATE ,
                h.SEQNO ,
                l.STOCKCODE ,
                l.ORD_QUANT ,
                ROW_NUMBER() OVER (PARTITION BY l.STOCKCODE ORDER BY h.ORDERDATE DESC, h.SEQNO DESC ) AS row
        FROM    SALESORD_HDR h 
        INNER JOIN  SALESORD_LINES l   ON   l.HDR_SEQNO = h.SEQNO
       ) A
WHERE ROW <= 3