2014-10-10 23 views
0

我有一張桌子,我想在下一個即將到來的生日(無視年份)訂購它們。 我用在這個答案中描述的方法:SQLite - 按照下一個即將到來的日期排序(忽略一年)

https://stackoverflow.com/a/20522025/2934340

OR

SQL代碼:

SELECT * 
FROM _table 
ORDER BY SUBSTR(DATE('NOW'), 6)>SUBSTR(birthdate, 6), SUBSTR(birthdate, 6); 

的問題是,我使用其他日期格式。在上面的答案中,日期格式是mm-dd,我想使用dd-mm。現在我的日期進行排序是這樣的:

17-10-1974 
03-10-1979 
29-02-1980 
20-10-1993 

我希望它排序是這樣的:

17-10-1974 
20-10-1993 
29-02-1980 
03-10-1979 (Because we are at 10-10-2014/past this date) 

我可以做我的代碼什麼改變實現這一目標?

+0

這不是的[支持的日期格式]一個(HTTP:// WWW。 sqlite.org/lang_datefunc.html)。 – 2014-10-10 14:58:29

+0

你是什麼意思? @CL。 – themanwithballs 2014-10-10 15:11:52

回答

1

一個簡單的方法來歸檔此,將月和日與SUBSTR()函數的切換:

SELECT * 
FROM _table 
ORDER BY SUBSTR(DATE('NOW'), 6)>(SUBSTR(birthdate, 4, 3) || SUBSTR (birthdate, 1, 2)), (SUBSTR(birthdate, 4, 3) || SUBSTR (birthdate, 1, 2)); 
+0

解決了它。先生非常感謝您! – themanwithballs 2014-10-11 13:54:27

0

只是一個快速的解決方案,我能想到的是以下幾點:

SELECT * 
FROM (SELECT * 
     FROM _table 
     WHERE (Substr(birthdate, 4, 2) = Substr(Date('now'), 6, 2) 
       AND Substr(birthdate, 1, 2) > Substr(Date('now'), 9, 2)) 
       OR (Substr(birthdate, 4, 2) != Substr(Date('now'), 6, 2)) 
     ORDER BY Substr(birthdate, 4, 2), 
        Substr(birthdate, 1, 2)) 
UNION ALL 
SELECT * 
FROM (SELECT * 
     FROM _table 
     WHERE Substr(birthdate, 4, 2) = Substr(Date('now'), 6, 2) 
       AND Substr(birthdate, 1, 2) < Substr(Date('now'), 9, 2) 
     ORDER BY Substr(birthdate, 1, 2)); 

讓我們假設今天是21-02,第一條語句將返回所有的生日,從22-02到31-01。然後第二個陳述將返回從01-02到20-02的生日。 Date('now')表示爲YYYY-MM-DD,這就是爲什麼我們將Substr(birthdate,4,2)Substr(Date('now',6,2)作比較的月份。 我們不得不在其他select語句中包含select語句,否則我們必須將ORDER BY放在整個語句的末尾,這當然是您不想要的東西。

相關問題