简体   繁体   English

每笔交易的最后记录

[英]Last record per transaction

I am trying to select the last record per sales order.我正在尝试 select 每个销售订单的最后一条记录。

My query is simple in SQL Server management.我的查询在 SQL 服务器管理中很简单。

SELECT *    
FROM DOCSTATUS

The problem is that this database has tens of thousands of records, as it tracks all SO steps.问题是这个数据库有数万条记录,因为它跟踪所有 SO 步骤。

ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

I would to see the most recent record per the SO我想查看每个 SO 的最新记录

 ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate   
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

Well I'm not sure how that table has two Name columns, but one easy way to do this is with ROW_NUMBER() :好吧,我不确定该表如何具有两个Name列,但一种简单的方法是使用ROW_NUMBER()

;WITH cte AS 
(
  SELECT *, 
    rn = ROW_NUMBER() OVER (PARTITION BY SO ORDER BY Systemdate DESC)
  FROM dbo.DOCSTATUS
)
SELECT ID, SO, SL, Status, Reason, ..., Systemdate
FROM cte WHERE rn = 1;

Also please always reference the schema , even if today everything is under dbo .请始终参考架构,即使今天一切都在dbo之下。

I think you can keep it this simple:我认为您可以保持简单:

SELECT *
FROM DOCSTATUS
WHERE ID IN (SELECT MAX(ID)
             FROM DOCSTATUS
             GROUP BY SO)

You want only the maximum ID from each SO.您只需要每个 SO 的最大 ID。

An efficient method with the right index is a correlated subquery:具有正确索引的有效方法是相关子查询:

select t.*
from t
where t.systemdate = (select max(t2.systemdate) from t t2 where t2.so = t.so);

The index is on (so, systemdate) .索引在(so, systemdate)上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM