最近4家供应商的股票详情

时间:2015-02-03 03:57:42

标签: sql sql-server

我正在尝试获取最近4家最新供应商的库存明细,最新价格等。这是SQL尝试但未获得结果。

SELECT S.Number, S.Description, S.BrandDescription, PL.ID, S.CatalogueDescription, S.InventoryUnitOfMeasure,  
                         S.TenderPrice, S.LastTenderedVendorId, S.Notes --, vendorNumber, VendorName, LastTransactionDate, po.OrderDate
FROM Stocks.Stock S LEFT OUTER JOIN Purchasing.PurchaseOrderLineItem PL on s.id = pl.StockId
                    inner join Purchasing.PurchaseOrder po on po.Id = pl.PurchaseOrderId
                    left join 
                    (select vendorNumber, VendorName, POLID, LastTransactionDate from
                        (
                        SELECT top 4 v.Number vendorNumber, v.Name VendorName, PLL.Id POLID, max(por.TransactionDate) as LastTransactionDate,
                        ROW_NUMBER() OVER(PARTITION BY v.Number ORDER BY max(por.TransactionDate) DESC) AS rk
                        FROM Purchasing.PurchaseOrderLineItem PLL 
                        inner join Purchasing.PurchaseOrder po on PLL.PurchaseOrderId = po.Id
                        inner join Purchasing.PurchaseOrderVendor POV on po.Id = POV.PurchaseOrderId
                        inner join Purchasing.Vendor V on pov.VendorId =  v.Id
                        left outer join Purchasing.PurchaseOrderReceipt POR on PLL.Id = por.PurchaseOrderLineItemId
                        group by v.Number, v.Name,PLL.Id
                        order by LastTransactionDate desc
                        ) A
                        where a.rk = 1) B on PL.Id = b.POLID

我最多需要4个最后的供应商,因此需要每个库存4行供应商详细信息。将报告组。 LINQ查询也可以。

1 个答案:

答案 0 :(得分:2)

从您的陈述中不清楚哪个表是主表,哪个表是详细信息,但这里是您要执行的操作的模板。你可以使用外部申请:

Select * from master m
outer apply (select top 4 * From Details d where m.Id = d.Id order by someColumns desc)o