sql—根据多列分组查找最近更新的行

p8ekf7hl  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(236)

我使用的是sqlserver和t-sql。
样本数据:
我有数据类似于下面的测试数据。

--===== Set the proper date format for the test data.
    SET DATEFORMAT dmy
;
--===== Create and populate the Test Table
   DROP TABLE IF EXISTS #TestTable
;
 CREATE TABLE #TestTable
        (
         Item       VARCHAR(10) NOT NULL
        ,GroupA     TINYINT     NOT NULL
        ,GroupB     SMALLINT    NOT NULL
        ,Updated    DATE        NOT NULL
        ,Idx        INT         NOT NULL
        )
;
 INSERT INTO #TestTable WITH (TABLOCK)
        (Item,GroupA,GroupB,Updated,Idx)
 VALUES  ('ABC',7,2020,'14/11/2019',8)  --Return this row
        ,('ABC',7,2020,'10/11/2019',7)
        ,('ABC',6,2019,'14/11/2019',6)  --Return this row
        ,('ABC',5,2018,'13/11/2019',5)  --Return this row
        ,('ABC',5,2018,'12/11/2019',4)
        ,('ABC',7,2018,'14/11/2019',3)  --Return this row
        ,('ABC',7,2019,'25/11/2019',2)  --Return this row
        ,('ABC',7,2019,'18/11/2019',1)
;
--===== Display the test data
 SELECT * FROM #TestTable
;

问题描述:
我需要帮助编写一个查询,该查询将返回标记为“--returnthisrow”的行。我知道如何写一个基本的选择,但不知道如何做到这一点。
问题的基础是为每个“组”行返回最新更新的行。行的“组”由item、groupa和groupb列的组合决定,我需要返回找到的完整行。

scyqe7ek

scyqe7ek1#

使用 row_number() :

select t.*
from (select t.*, row_number() over (partition by item, groupa, groupb order by updated desc) as seq
      from table t
     ) t
where seq = 1;
r6hnlfcb

r6hnlfcb2#

select table.Item,table.GroupA,table.GroupB,table.Updated,Idx
FROM    (select Item,GroupA,GroupB,max(Updated) Updated
         from table 
         group by Item,GroupA,GroupB) a
inner join table 
on(a.Item = table.Item and a.GroupA = table.GroupA and a.GroupB = table.GroupB and 
   a.Updated = table.Updated)

相关问题