我正在努力在 SQLite 中找到一个有效的查询,它将在他们即将到来的生日中返回我的记录以及它将发生的天数
CREATE TABLE contact_birthday ('contact_id' varchar,'data1' varchar,'display_name' varchar)
data1
以 YYYY-MM-DD 格式保存生日就像是:
"1986-06-28","Angel","0"
"1979-06-29","Bea","1"
"1984-07-02","John","4"
"1984-06-26","Mark","364"
我发现了一些其他结果,但它们适用于 MySQL,或者不在 SQLite 中的 SQL Server。
如果没有用户定义的函数,SQLite 中的查询将如何?
最佳答案
我使用 julianday 让它工作(获得“一天”计数 AFAIK 的唯一方法)
select name,
julianday(strftime('%Y', 'now')||strftime('-%m-%d', data1))-julianday('now') as birthday
from foo
where birthday between -1 and 30;
我的结果:Angel|-0.479438499547541
Bea|0.520561488810927
John|3.52056147716939
快速解释:
julianday(strftime('%Y', 'now')
<- 这会拉出当前年份,因此 data1 的 julianday 不考虑 80 年代以来的年份||strftime('-%m-%d', data1))
<- 这将实际生日的月/日连接到当年where birthday between -1 and 30;
<- -1 确保您将一直看到“今天”的结果。 30 是您希望提前查看的最大天数。编辑 1 :
这是一个使用 1970 纪元以来的秒数而不是儒略日的修改:
select name,
(strftime('%s',strftime('%Y', 'now')||strftime('-%m-%d', data1))-strftime('%s','now'))/86400.0 as birthday
from foo
where birthday between -1 and 30
order by birthday;
结果:Angel|-0.487118055555556
Bea|0.512881944444445
John|3.51288194444444
编辑 2 : [奔腾10]
包括正确的本地时间
select data1,display_name,
(strftime('%s',strftime('%Y', 'now','localtime')||strftime('-%m-%d', data1))-strftime('%s','now','localtime'))/86400.0 as birthday
from contact_birthday
order by birthday asc
编辑 3 : [奔腾10]包括订单,如果从今天到明年这个时间正好是 365 天
** 仍然需要 365 天的动态计算,因为闰年可以是 366
select data1,display_name,
((strftime('%s',strftime('%Y', 'now','localtime')||strftime('-%m-%d', data1))-strftime('%s','now','localtime'))/86400.0+1+365) % 365 as birthday
from contact_birthday
order by birthday asc
编辑 4 :[马特]这实际上可能对您有用:
select data1,name,
365-(strftime('%s',strftime('%Y', 'now', '+1 year', 'localtime')||strftime('-%m-%d', data1))-strftime('%s','now','localtime'))/86400.0 as birthday
from foo
order by birthday asc
编辑 5 : [奔腾10]答案
select data1,display_name,
((strftime('%s',strftime('%Y', 'now','localtime')||strftime('-%m-%d', data1))-strftime('%s','now','localtime'))/86400.0+1+((strftime('%s','now', 'localtime','+1 year')-strftime('%s','now', 'localtime'))/86400.0)) % ((strftime('%s','now', 'localtime','+1 year')-strftime('%s','now', 'localtime'))/86400.0) as indays
from contact_birthday
order by indays asc
结果:1984-07-02|John|-3.65773148148151
1979-06-29|Bea|-0.657731481481505
1986-06-28|Angel|0.342268518518495
1984-06-26|Mark|2.34226851851849
1987-02-16|Matt|132.342268518519
因此,今年即将到来的生日将是负数(例如约翰的 future 3 天),今年已经过去的生日将是正数。
这应该允许正确的排序。
关于sql - 如何在即将到来的生日订单中获取记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3131840/