如何使用 SQLite 编写自定义排序

How to write a custom sort using SQLite

我有一个table

Create Table Part(Part TEXT, Rev TEXT, DateCode Date, Unique(Part,Rev))

是否可以按 DateCode DESC 执行自定义排序,但对于具有相同 Part 的记录应该分组在一起,例如结果:

PART_1, B, 2022-02-14
PART_1, A, 1999-01-11
PART_2, C, 2000-02-24
PART_2, B, 1998-11-12
PART_2, A, 1998-11-10

我的直觉告诉我必须用

完成
ORDER BY CASE WHEN....
 

但是我的知识还不够好,无法继续。请帮助我。

您可以在 ORDER BY 子句中使用 MAX() window 函数来获取每个部分的最大值 DateCode 并按降序排序:

SELECT *
FROM Part
ORDER BY MAX(DateCode) OVER (PARTITION BY Part) DESC,
         Part, -- just in case 2 different parts have the same max DateCode
         DateCode DESC;

参见demo

对我来说,这看起来很简单,先按部分排序,然后按日期排序

SELECT * FROM Part order by Part,DateCode Desc

本例中用于 SQLlite 的 Sqlfiddle here 我想我肯定错过了一些东西..