Select 来自 peewee 的查询

Select from a query with peewee

我在使用 peewee 执行以下查询时遇到了一些问题:

SELECT *
FROM (
    SELECT datas.*, (rank() over(partition by tracking_id order by date_of_data DESC)) as rank_result
    FROM datas
    WHERE tracking_id in (1, 2, 3, 4, 5, 6)
)
WHERE rank_result < 3;

我已尝试执行以下操作:

subquery = (Datas.select(Datas.tracking, Datas.value, Datas.date_of_data,
                                 fn.rank().over(partition_by=[Datas.tracking],
                                                order_by=[Datas.date_of_data.desc()]).alias('rank'))
                    .where(Datas.tracking.in_([1, 2, 3, 4, 5, 6])))
result = (Datas.select()
               .from_(subquery)
               .where(SQL('rank') < 3))

但是因为我在做“Model.select()”,所以我得到了 SQL SELECT 中我不想要的和不想要的所有字段让我的查询工作。 这是我的 table:

的架构
CREATE TABLE IF NOT EXISTS "datas" 
(
    "id" INTEGER NOT NULL PRIMARY KEY, 
    "tracking_id" INTEGER NOT NULL, 
    "value" INTEGER NOT NULL, 
    "date_of_data" DATETIME NOT NULL, 
    FOREIGN KEY ("tracking_id") REFERENCES "follower" ("id")
);
CREATE INDEX "datas_tracking_id" ON "datas" ("tracking_id");

谢谢!

您可能想在子查询上使用 .select_from() 方法:

subq = (Datas.select(Datas.tracking, Datas.value, Datas.date_of_data,
                     fn.rank().over(partition_by=[Datas.tracking],
                                    order_by=[Datas.date_of_data.desc()]).alias('rank'))
                    .where(Datas.tracking.in_([1, 2, 3, 4, 5, 6])))

result = subq.select_from(
    subq.c.tracking, subq.c.value, subq.c.date_of_data,
    subq.c.rank).where(subq.c.rank < 3)

生产:

SELECT "t1"."tracking", "t1"."value", "t1"."date_of_data", "t1"."rank" 
FROM (
    SELECT "t2"."tracking", 
           "t2"."value", 
           "t2"."date_of_data", 
           rank() OVER (
              PARTITION BY "t2"."tracking" 
              ORDER BY "t2"."date_of_data" DESC) AS "rank" 
    FROM "datas" AS "t2" 
    WHERE ("t2"."tracking" IN (?, ?, ?, ?, ?, ?))) AS "t1" 
WHERE ("t1"."rank" < ?)