开发者

SQLite: Select all date-value-pairs where the distance between each date and the first date is a multiple of a specific period

I am working with SQLite and Python and try to get these specific dates (and corresponding values). I think an example explainst best what I am looking for. Consider selecting from this 开发者_如何学Godata:

-(2011-01-02, 4.0)
-(2011-01-14, 5.0)
-(2011-02-02, 5.5)
-(2011-02-07, 6.5)
-(2011-02-12, 7.0)
-(2011-02-15, 4.0)
-(2011-03-02, 2.5)
-(2011-03-09, 3.5)

with a period-distance of one month (or a multiple) between the first date and all the dates we are looking for we return this data:

-(2011-01-02, 4.0)
-(2011-02-02, 5.5)
-(2011-03-02, 2.5)

I was looking for an SQL-statement which provides me with this data, if that is possible.

Additional question: if there is no date-point which is exactly a multiple of a month away from the initial date, how can I get the nearest date in my database?

I hope that my explanation is clear enough. If not, thanks for telling.


It sounds like this won't be a flexible enough solution for your needs, but to answer your question directly, here is a query that gets you what you need.

Also, since you didn't specify table/column names, my test table I used is called foo, and has columns created and value.

select
    foo.created, foo.value
from 
    -- Subquery to pick first record to base rest of query on
    (
        select
            created,
            strftime('%d', created) as day
        from
            foo
        order by
            created
        limit 1
    ) as bar

    -- Join all rows in foo that are greater than that found in 'bar'
    -- and has the same day of the month.
    join foo
        on foo.created >= bar.created
           and strftime('%d', foo.created) = bar.day

Results:

2011-01-02|4.0
2011-02-02|5.5
2011-03-02|2.5

NOTE - this is probably fairly inefficient, due to all the strftimes being done (I'm assuming no index can be used here).

NOTE 2 - This query doesn't deal with intervals other than exactly one month, do anything special if two records have the same date, or recognize when there are gaps in the the data (example: if the 2011-02-02 date was missing, it would still return the 2011-03-02 date).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜