Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a custom sort using SLQLite

I have a single table

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

Is it possible to perform a custom sort by DateCode DESC but for the records with same Part should be grouped together for example result:

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

My instinct tells me it must be done with

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ORDER BY CASE WHEN....
 

But my knowledge is not good enough to continue. Please help me.

>Solution :

You can use MAX() window function in the ORDER BY clause to get the max DateCode of each part and sort by that descending:

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;

See the demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading