最终订购每件商品的价格

时间:2015-02-23 10:26:59

标签: sql sql-server select subquery

我使用Microsoft SQL,更具体地说是LinnWorks进行订单管理。我想提取每个[SKU]的最后一个订单和为它支付的[价格]。我已经到目前为止,但我认为我的方法是不正确的,因为我为每个付出的价格得到了不同的行。

这是LinnWorks表格布局;

LinnWorks Table layout

这就是我所尝试的,在添加价格之前一切正常;

SELECT
    si.ItemNumber AS [SKU],
    DATEDIFF("d",MAX(o.dReceievedDate), GETDATE()) AS [Last Ordered],
    oi.fpricePerUnit AS [Price],
    si.RetailPrice AS [MSRP]
FROM [Order] o
INNER JOIN OrderItem oi 
    on o.pkOrderID = oi.fkOrderID
LEFT OUTER JOIN StockItem si 
    on si.pkstockItemId = oi.fkStockItemID_processed
WHERE o.Source = 'EBAY'
GROUP BY si.ItemNumber, oi.fpricePerUnit, si.RetailPrice

我明白为什么会这样做(分组),但我不知道解决问题的方法。

1 个答案:

答案 0 :(得分:2)

;WITH CTE AS
(
SELECT
    si.ItemNumber AS [SKU],
    DATEDIFF("d",o.dReceievedDate, GETDATE()) AS [Last Ordered],
    row_number() over (PARTITION BY si.ItemNumber, oi.fpricePerUnit, si.RetailPrice 
       ORDER BY o.dReceievedDate DESC) rn,
    oi.fpricePerUnit AS [Price],
    si.RetailPrice AS [MSRP]
FROM [Order] o
INNER JOIN OrderItem oi 
    on o.pkOrderID = oi.fkOrderID
LEFT OUTER JOIN StockItem si 
    on si.pkstockItemId = oi.fkStockItemID_processed
WHERE o.Source = 'EBAY'
)
SELECT * FROM CTE WHERE rn = 1