您需要通过在TransactionCode 列上对它们进行分区来为表中的每一行分配行号,然后按降序对它们进行排序ActionDate,以便您在该部分的顶部获得最新的事务。一旦基于此逻辑分配了行号,您就可以从派生表输出中仅过滤出具有 1 的rownum 值的行。这将获取所有交易代码。您可以根据需要在下面的查询中添加过滤条件。
Click here to view the demo in SQL Fiddle
脚本:
CREATE TABLE dbo.TransTable
(
IdKey INT NOT NULL IDENTITY
, TransactionCode VARCHAR(10) NOT NULL
, ActionDate DATETIME NOT NULL
);
INSERT INTO dbo.TransTable (TransactionCode, ActionDate) VALUES
('code 1', '2012-04-27 01:04:12.467'),
('code 1', '2012-04-22 09:16:29.354'),
('code 2', '2012-04-12 11:04:27.751'),
('code 1', '2012-06-19 12:27:12.232'),
('code 2', '2012-04-04 05:22:17.467'),
('code 3', '2012-05-01 08:49:12.951'),
('code 3', '2012-05-13 06:12:12.234');
SELECT IdKey
, TransactionCode
, ActionDate
FROM
(
SELECT IdKey
, TransactionCode
, ActionDate
, ROW_NUMBER() OVER (
PARTITION BY TransactionCode
ORDER BY ActionDate DESC
) rownum
FROM dbo.TransTable
WHERE ActionDate < GETDATE()
) t1 WHERE rownum = 1;
输出:
IdKey TransactionCode ActionDate
----- --------------- -----------------------
1 code 1 2012-04-27 01:04:12.467
3 code 2 2012-04-12 11:04:27.750