Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

python - Query the most recent row with a lag function

I am trying to make a list of all the Result's with the most recent related Batch.date, while also filtering only negative numbers when comparing Result.price to the second most recent Result using fn.LAG.

This is what I have so far using peewee with sqlite3:

    difference = Result.price - fn.LAG(Result.price, 1).over(partition_by= [Itinerary.length, Result.dest,
                                                             Itinerary.period, Batch.departure], order_by = Batch.date.asc())
        
    fd = (Result
            .select(Batch.departure.alias("departure"),
                    Batch.date.alias("date"),
                    Itinerary.period.alias("period"),
                    Itinerary.length.alias("length"),
                    Result.price.alias("price"),
                    Result.dest.alias("dest"),
                    difference.alias('diff'))
            .join(Batch)
            .switch(Result)
            .join (Itinerary))

    get_all = (Result
                .select(fd.c.departure, fd.c.date, fd.c.period,
                        fd.c.length, fd.c.price, fd.c.dest, fd.c.diff)
                .from_(fd)
                .where(fd.c.diff < 0))

My models are:

class BaseModel(Model):
    class Meta:
        database = db

class Batch(BaseModel):
    departure = CharField()
    date = DateField(default=date.today())

class Itinerary(BaseModel):
    period = CharField()
    length = CharField()

class Result(BaseModel):
    dest = CharField()
    price = IntegerField()
    batch = ForeignKeyField(Batch, backref='search')
    itin = ForeignKeyField(Itinerary, backref='result')

I'm pretty lost at the moment.. I couldn't get fn.MAX and a group_by() to work in conjunction with the difference calculation. I think I might need to make a second sub-query?

question from:https://stackoverflow.com/questions/65865514/query-the-most-recent-row-with-a-lag-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...