[英]Get last transaction per product
I have typical order header and order line tables. 我有典型的订单标题和订单行表。 This is the simplified DDL (there are more fields, but not important for this question)
这是简化的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]
I need to run a query in sql server where it returns in each warehouse, the last order line per item. 我需要在SQL Server中运行查询,该查询在每个仓库中返回,每个项目的最后一个订单行。
so 所以
warehouse 1
item1, Order20, line 3
item2, Order 40, line 1
warehouse 2
item1, Order25, line 1
etc... 等等...
multiple orders in the same warehouse could exist on the same date for the same item, in this case it needs to be the latest order. 同一物料在同一日期可能存在同一仓库中的多个订单,在这种情况下,它必须是最新的订单。 I am not using DateTime for orderDate, it's just a date.
我没有使用DateTime作为orderDate,这只是一个日期。
Is there an easy way to do this ? 是否有捷径可寻 ?
Without usable Sample data, or DDL, this is a guess. 如果没有可用的样本数据或DDL,这是一个猜测。 If it doesn't work, please edit your post and reply to this answer.
如果不起作用,请编辑您的帖子并回复此答案。
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;
Note that you haven't defined how to determine what is the latest order if they are on the same day, thus I haven't considered it. 请注意,您还没有定义如何确定同一天的最新订单,因此我没有考虑。 You'll need to edit the
ORDER BY
to ensure it works for your data if that is the problem (or, again, edit your post). 如果出现问题,您需要编辑
ORDER BY
以确保它适用于您的数据(或者再次编辑您的帖子)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.