[英]Getting oldest record from SQL Server using T-SQL
I have a T-SQL query where I need to find the oldest date record.我有一个 T-SQL 查询,我需要在其中找到最旧的日期记录。 I have written it like this:
我是这样写的:
SELECT
T0.ItemCode, T0.OpenQty AS 'Qty', MIN(T1.DocDate) AS 'DocDate',
T1.DocNum, T1.CardCode, T1.SlpCode AS 'Sales Person', T0.WhsCode
FROM
RDR1 T0
INNER JOIN
ORDR T1 ON T0.DocEntry = T1.DocEntry
WHERE
T0.linestatus = 'O'
GROUP BY
T0.ItemCode, T0.OpenQty , T1.DocNum, T1.CardCode, T1.SlpCode , T0.WhsCode
but it is not returning the oldest date record.但它没有返回最旧的日期记录。
Data is shown in this screenshot:数据显示在此屏幕截图中:
You can use ROW_NUMBER()
to rank the records by ascending T1.DocDate
in a inner query, and then select the oldest in the outer query:您可以使用
ROW_NUMBER()
在内部查询中通过升序T1.DocDate
对记录进行排名,然后在外部查询中使用最旧的 select 对记录进行排名:
Select *
From (
Select
T0.ItemCode,
T0.OpenQty as 'Qty',
T1.DocDate,
T1.DocNum,
T1.CardCode,
T1.SlpCode as 'Sales Person',
T0.WhsCode,
Row_Number() Over(Order By T1.DocDate) rn
From RDR1 T0
Inner Join ORDR T1 on T0.DocEntry = T1.DocEntry
Where T0.linestatus = 'O'
) x
Where rn = 1
This will give you the oldest record in the table.这将为您提供表中最旧的记录。 If you need to get the oldest record per group, then you can add a
PARTITION BY
clause to the ROW_NUMBER()
function.如果您需要获取每个组中最旧的记录,则可以在
ROW_NUMBER()
function 中添加PARTITION BY
子句。
Note: this also assumes that T1.DocDate
is of a date-like datatype, which seems to be (and should be) the case by looking at your sample data.注意:这还假设
T1.DocDate
是类似日期的数据类型,通过查看您的示例数据似乎是(并且应该是)这种情况。
Why are you writing Self join?你为什么要写自我加入? If you need to get 10 oldest record from table then just sort the table according date in ascending order and list top 10 rows.
如果您需要从表中获取 10 条最旧的记录,则只需按日期按升序对表进行排序并列出前 10 行。
For Example -例如 -
Select top 10 T0.ItemCode, T0.OpenQty as 'Qty', T1.DocDate as 'DocDate', T1.DocNum, T1.CardCode, T1.SlpCode as 'Sales Person', T0.WhsCode
From RDR1 T0
Where T0.linestatus = 'O'
order by T1.DocDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.