Last active
July 23, 2019 15:52
-
-
Save andrey-helldar/f0f8f51af2985d849f6ccf6b57abef62 to your computer and use it in GitHub Desktop.
Sort data in two columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Creating table: | |
*/ | |
CREATE TABLE sql_test | |
( | |
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, | |
started_at TIMESTAMP NULL, | |
created_at TIMESTAMP | |
); | |
/* | |
* Storing data: | |
*/ | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:30'); | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:31'); | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:32'); | |
INSERT INTO sql_test (created_at, started_at) VALUES ('2019-07-23 18:33', '2019-08-27 04:07'); | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:34'); | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:35'); | |
INSERT INTO sql_test (created_at, started_at) VALUES ('2019-07-23 18:33', '2019-06-12 04:07'); | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:36'); | |
INSERT INTO sql_test (created_at, started_at) VALUES ('2019-07-23 18:37', '2019-08-24 08:15'); | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:38'); | |
INSERT INTO sql_test (created_at) VALUES ('2019-07-23 18:39'); | |
/* | |
* Query: | |
*/ | |
SELECT | |
* | |
FROM sql_test | |
ORDER BY IF(started_at IS NULL, created_at, started_at) DESC | |
/* | |
* Result: | |
* | |
* | id | started_at | created_at | | |
* | 4 | 2019-08-27 04:07:00 | 2019-07-23 18:33:00 | | |
* | 9 | 2019-08-24 08:15:00 | 2019-07-23 18:37:00 | | |
* | 11 | | 2019-07-23 18:39:00 | | |
* | 10 | | 2019-07-23 18:38:00 | | |
* | 8 | | 2019-07-23 18:36:00 | | |
* | 6 | | 2019-07-23 18:35:00 | | |
* | 5 | | 2019-07-23 18:34:00 | | |
* | 3 | | 2019-07-23 18:32:00 | | |
* | 2 | | 2019-07-23 18:31:00 | | |
* | 1 | | 2019-07-23 18:30:00 | | |
* | 7 | 2019-06-12 04:07:00 | 2019-07-23 18:33:00 | | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment