我正在使用SQL Server 2012
我有下表
create table tableA
(
ID uniqueidentifier,
CustomerId uniqueidentifier,
VisitDate DATETIME,
[Mark] int
);
insert into tableA values
('80D8F17A-A581-4B62-8245-45276A8422FD','0BD6B2E3-F8DE-463D-8D10-000000D49DC0','2015-09-28 15:23:00.000',100),
('EBBC88DD-C4F9-480C-9482-5CF72F912237','CE029ECC-0546-4B8B-854B-00000814BB55','2015-09-28 15:10:36.000',200),
('06A460E4-0702-4872-B3DF-77FF37E9345A','CE029ECC-0546-4B8B-854B-00000814BB55','2015-09-28 15:10:36.000',150),
('7F2F5C41-E585-454A-B9E1-3DC4DF7D4A04','0BD6B2E3-F8DE-463D-8D10-000000D49DC0','2015-09-29 15:00:00.000',300),
('0271DD70-422D-4117-8CBE-2C5DA2B84E2C','1E8E91D3-C58C-4C70-86AD-00012C9D5B66','2015-09-30 15:00:00.000',200),
('91D2BEF4-83EA-4A63-A561-FF32CF6B7C66','1E8E91D3-C58C-4C70-86AD-00012C9D5B66','2015-09-30 16:00:00.000',100),
('F3C129C7-E4B2-40CA-8A58-973E6AA5D379','1E8E91D3-C58C-4C70-86AD-00012C9D5B66','2015-09-30 17:00:00.000',100),
('AB20335C-78C6-46A6-88D8-38AC2ED7D023','E60D531F-3F3F-4129-A9AC-00008D20BD36','2015-09-01 12:12:12.000',200);
我可以像每个客户一样获得LastVisitDate
Select CustomerId,MAX(VisitDate) as lastVisitDate From tableA
GROUP BY CustomerId
但是我希望我的输出只是与我的组中获得的上述行相对应的主键ID。
我该怎么做?
答案 0 :(得分:2)
您可以使用ROW_NUMBER
:
WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY CustomerId
ORDER BY VisitDate DESC)
FROM tableA
)
SELECT ID
FROM CTE
WHERE RN = 1;