我使用的是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列的组合决定,我需要返回找到的完整行。
2条答案
按热度按时间scyqe7ek1#
使用
row_number()
:r6hnlfcb2#