2014-10-10 42 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放在整个语句的末尾,这当然是您不想要的东西。

相关问题