【问题标题】:Select which has the latest date for each item选择每个项目的最新日期
【发布时间】:2021-09-16 13:49:44
【问题描述】:

我有 2 张桌子,比如说 tableA 和 tableB。

表 A

create table tableA
(ID int, DocumentDate datetime2, DocumentName varchar(3), ItemID int);

insert into tableA (ID, DocumentDate, DocumentName, ItemID)
values (1, '2019-08-01 12:00:00', 'A-1', 1),
(2, '2020-05-12 13:00:00', 'B-2', 1),
(3, '2021-07-01 14:00:00', 'C-3', 1),
(4, '2020-01-01 12:00:00', 'D-4', 2),
(5, '2021-02-01 13:00:00', 'E-5', 2),
(6, '2021-07-02 14:00:00', 'F-6', 2);

这是B表

create table tableB
(ID int, ItemCode varchar(3));

insert into tableB (ID, ItemCode)
values (1, 'AAA'),
(2, 'BBB');

这是我的 SQL Server 查询

select 
    A.ID, 
    A.DocumentDate, 
    A.DocumentName, 
    B.ItemCode 
from tableA A
left join tableB B on B.ID = A.ItemID

结果should be like this

我想为AAA选择第3个,为BBB选择第6个,日期最晚。 谢谢。

【问题讨论】:

  • "结果应该是this"?这是您通过查询获得的结果(所有六行)。你不想要两个吗?你的下一段似乎是这样说的。请不要使用图像。将文本格式的表格粘贴到您的请求中。

标签: sql sql-server


【解决方案1】:

你可以使用apply:

select b.*, a.*
from tableB b outer apply
     (select top (1) a.*
      from tableA a
      where a.itemId = b.Id
      order by a.documentdate desc
     ) a;

使用tableA(item, documentdate) 上的索引,这通常会有很好的性能

【讨论】:

    【解决方案2】:

    看起来很简单:

    WITH cteDocuments As
    (
        SELECT
            ID,
            DocumentDate,
            DocumentName,
            ItemID,
            ROW_NUMBER() OVER (PARTITION BY ItemID ORDER BY DocumentDate DESC) As RN
        FROM
            tableA
    )
    SELECT
        A.ID,
        A.DocumentDate,
        A.DocumentName,
        B.ItemCode
    FROM
        cteDocuments As A
        LEFT JOIN tableB As B ON B.ID = A.ItemID
    WHERE
        A.RN = 1
    ;
    

    ROW_NUMBER

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多