假设有一个数据集包含以下列: Name (姓名), Appointment Date (约会日期) 和 Appointment Result (约会结果)。我们想要按照以下顺序进行排序:首先按照约会日期(从最新到最旧)排序,然后按照姓名排序(从 A 到 Z)。
查询语句如下:
SELECT Name, MAX([Appointment Date]) AS LatestAppointment, [Appointment Result] FROM [Table] GROUP BY Name, [Appointment Result] ORDER BY LatestAppointment DESC, Name ASC
其中,MAX() 函数用于确定每个人的最新约会日期。GROUP BY 语句用于根据姓名和约会结果将数据分组。ORDER BY 语句首先按照 LatestAppointment(最新约会日期)降序排列,然后按照 Name(姓名)升序排列。
这将返回一个结果集,其中每个条目都包含一个人的姓名、他们的最新约会日期和最新约会结果。
示例代码:
CREATE TABLE [Table] ( [Name] NVARCHAR(50), [Appointment Date] DATE, [Appointment Result] NVARCHAR(50) );
INSERT INTO [Table] ([Name], [Appointment Date], [Appointment Result]) VALUES ('Adam', '2021-09-15', 'No show'), ('Bob', '2021-10-01', 'Satisfied'), ('Adam', '2021-10-08', 'Satisfied'), ('Cathy', '2021-10-05', 'Satisfied'), ('Bob', '2021-10-11', 'No show');
SELECT Name, MAX([Appointment Date]) AS LatestAppointment, [Appointment Result] FROM [Table] GROUP BY Name, [Appointment Result] ORDER BY LatestAppointment DESC, Name ASC;
这将返回以下结果:
Name | LatestAppointment | Appointment Result -------+------------------+------------------- Adam | 2021-10-08 | Satisfied Bob | 2021-10-11 | No