获取每个产品的最后一笔交

时间:2017-12-20 12:32:52

标签: sql sql-server

我有典型的订单表和订单行表。 这是简化的DDL(有更多字段,但对于这个问题并不重要)

CREATE TABLE [dbo].[OrderHeader](
    [id] [nvarchar](50) NOT NULL,
    [voucherDate] [datetime] NOT NULL,
    [voucherNumber] [bigint] NOT NULL,
    [voucherType] [nvarchar](50) NOT NULL,
    [account] [nvarchar](50) NULL,
    [po] [nvarchar](50) NULL,
    [total] [decimal](19, 3) NOT NULL,
    [status] [tinyint] NOT NULL,
    [discount] [decimal](19, 3) NOT NULL,
    [rounding] [decimal](19, 3) NULL,
    [net] [decimal](19, 3) NOT NULL,
    [warehouse] [nvarchar](50) NULL,
 CONSTRAINT [PK_OrderHeader] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [dbo].[OrderLine](
    [header] [nvarchar](50) NOT NULL,
    [line] [int] NOT NULL,
    [item] [nvarchar](50) NULL,
    [quantity] [decimal](19, 3) NOT NULL,
    [price] [decimal](19, 3) NOT NULL,
    [discount] [decimal](19, 3) NOT NULL,
    [total] [decimal](19, 3) NOT NULL,
 CONSTRAINT [PK_OrderLine] PRIMARY KEY CLUSTERED 
(
    [header] ASC,
    [line] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

我需要在sql server中运行一个查询,它在每个仓库中返回,即每个项目的最后一个订单行。

所以

warehouse 1
       item1, Order20, line 3
       item2, Order 40, line 1

   warehouse 2
        item1, Order25, line 1

等...

同一仓库中的多个订单可能存在于同一个项目的同一日期,在这种情况下,它需要是最新的订单。我没有使用DateTime作为orderDate,它只是一个日期。

有一种简单的方法吗?

1 个答案:

答案 0 :(得分:0)

没有可用的样本数据或DDL,这是一个猜测。如果它不起作用,请编辑您的帖子并回复此答案。

WITH CTE AS (
    SELECT OH.Warehouse,
           OL.Item,
           OH.OrderNbr,
           OH.LineNbr,
           ROW_NUMBER() OVER (PARTITION BY OH.Warehouse, OL.LineNbr ORDER BY OrderDate) AS RN
    FROM OrderHeader OH
         JOIN OrderLine OL ON OH.OrderNbr = OL.OrderHbr)
SELECT Warehouse,
       Item,
       OrderNbr,
       LineNbr
FROM CTE
WHERE RN = 1;

请注意,您尚未定义如何在同一天确定最新订单是什么,因此我没有考虑过。您需要修改ORDER BY以确保它适用于您的数据(如果这是问题)(或者​​,再次编辑您的帖子)。