SQLite查询根据当前日期对即将到来的生日进行排序

时间:2013-03-26 04:58:21

标签: sql sqlite

我的日期列是整数:

myDate.getTime() //long saved in db

在我研究如何最好地排序即将到来的生日时,我发现了这个: MySQL query to sort upcoming birthdays based on current date

我试图将解决方案翻译成SQLite语法,但没有运气。 有人想让我朝着正确的方向前进吗?

我甚至无法获得例如时间戳的月份:

strftime('%m', birthday) //unexpected value (dec = 1, jan = 1, jan = 6)
strftime('%m', 'now') // as expected (mar = 3)

任何帮助表示感谢。

更新 好的,现在我真的搞得一团糟:

cur = db.rawQuery("SELECT "
                        + "(strftime('%Y','now') - strftime('%Y',datetime(("+BIRTHDATE+"/1000), 'unixepoch', 'localtime'))) AS age,"
                        + "date((" + BIRTHDATE + "/1000),'+' || age || ' year') AS currbirthday,"
                        + "date((" + BIRTHDATE + "/1000),'+' || age+1 || ' year') AS nextbirthday"
                    + " FROM " + TABLE
                    + " ORDER BY CASE" 
                        + " WHEN currbirthday < date('now') THEN nextbirthday"
                        + " ELSE  currbirthday" 
                    + " END", null); 

错误:“没有这样的列时代”

好吧,好吧,我尝试将整个表达式计算“age”放在concat中,但结果很奇怪(age存储正确的值):

Log.d("bdate", contact.getFirstname() + ": currbday=" + cur.getString(1));
Log.d("bdate", contact.getFirstname() + ": nextbday=" + cur.getString(2));
  

Samantha:currbday = -5705--6--29

     

萨曼莎:nextbday = -5704--6--29

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

如果有人想知道,这是我的解决方案:

cur = db.rawQuery("SELECT "
                        + "date(strftime('%Y', 'now','localtime')||strftime('-%m-%d', datetime(("+BIRTHDATE+"/1000), 'unixepoch', 'localtime'))) as currbirthday,"
                        + "date(strftime('%Y', 'now','localtime')||strftime('-%m-%d', datetime(("+BIRTHDATE+"/1000), 'unixepoch', 'localtime')),'+1 year') as nextbirthday"
                    + " FROM " + TABLE
                    + " ORDER BY CASE" 
                        + " WHEN currbirthday < date('now') THEN nextbirthday"
                        + " ELSE  currbirthday" 
                    + " END", null); 

答案 1 :(得分:0)

我找到了一种使用不同方法的解决方案,该方法可以正确地适用于我认为的任何极端情况。它根据一年中的某天计算剩余天数,如果生日是第二年,则更正结果:

SELECT
    *, 
    strftime('%j', birthday) - strftime('%j', 'now') AS days_remaining
FROM
    person
WHERE :n_days >= CASE
    WHEN days_remaining >= 0 THEN days_remaining
    ELSE days_remaining + strftime('%j', strftime('%Y-12-31', 'now'))
    END
;