2
SELECT        TOP 100 PERCENT soheader.custid,SOHeader.OrdNbr, SOLine.InvtID, SOLine.Descr,SOLine.QtyOrd
FROM            SOHeader INNER JOIN
                         SOLine ON SOHeader.OrdNbr = SOLine.OrdNbr
WHERE        (SOHeader.OrdDate >= CONVERT(DATETIME, '2013-06-01 00:00:00', 102)) AND (SOHeader.OrdDate <= GETDATE()) AND (SOHeader.CustID = '69065')
ORDER BY SOLine.InvtID, SOHeader.OrdNbr

这是我的样本数据

69065  WO0175279  69407  Jazzy Laces White 3
69065  WO0175393  69407  Jazzy Laces White 6
69065  WO0175393  69407  Jazzy Laces White 9

现在我想知道如何获得第一次订购后订购的该商品的总数量。我不想在上面的第一条记录中包含 3 的数量。我只想在第一次重新订购中包含 6 的数量,在第二次重新订购中包含 9 的数量,这等于 15 的数量。

69065 是客户 ID

WO##### 是订单编号

69407 是库存 ID

4

2 回答 2

2
SELECT  invtId, SUM(QtyOrd)
FROM    (
        SELECT  invtId,
                qtyOrd,
                ROW_NUMBER() OVER (PARTITION BY invtId ORDER BY h.ordDate, h.ordNbr) rn
        FROM    soLine l 
        JOIN    soHeader h
        ON      h.ordNbr = l.ordNbr
        WHERE   l.custId = 69065
        ) q
WHERE   rn > 1
GROUP BY
        invtId
于 2013-09-19T16:24:25.117 回答
0
WITH cl
as
(select *, ROW_NUMBER() OVER (PARTITION BY InvtID ORDER BY QtyOrd) rn
from t)

select InvtID, QtyOrd, 
(select SUM(QtyOrd) from cl oo 
where o.InvtID = oo.InvtID and o.rn -1 > 0
and rn between o.rn -1 and o.rn) as 'sm'
from cl o

这是关于SqlFiddle的演示。

于 2013-09-19T17:27:58.147 回答