您需要通过在TransactionCode
列上对它们进行分区来为表中的每一行分配行号,然后ActionDate
按降序对它们进行排序,以便您在该部分的顶部获得最新的事务。根据此逻辑分配行号后,您可以仅从派生表输出中过滤掉rownum
值为1的行。这将获取所有交易代码。您可以根据需要在以下查询中添加过滤条件。
单击此处查看 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