[英]SQLAlchemy: Select rows, grouped by a date column, whose datetime column is most recent for each date
Given the following table in a PostgreSQL database.给定 PostgreSQL 数据库中的下表。
value![]() |
created_at ![]() |
date![]() |
---|---|---|
2 ![]() |
2022-02-01 01:01:01 ![]() |
2022-03-15 ![]() |
10 ![]() |
2022-02-15 01:01:01 ![]() |
2022-03-15 ![]() |
5 ![]() |
2022-02-02 01:01:01 ![]() |
2022-03-16 ![]() |
6 ![]() |
2022-02-16 01:01:01 ![]() |
2022-03-16 ![]() |
How can you write sqlalchemy code which:您如何编写 sqlalchemy 代码:
date
columndate
列分组created_at
value for each datecreated_at
值The output of above query should be the following:上述查询的输出应如下所示:
value![]() |
created_at ![]() |
date![]() |
---|---|---|
10 ![]() |
2022-02-15 01:01:01 ![]() |
2022-03-15 ![]() |
6 ![]() |
2022-02-16 01:01:01 ![]() |
2022-03-16 ![]() |
I have tried the following query:我尝试了以下查询:
query = (
select(
func.max(TABLE.created_at),
TABLE.date,
TABLE.value
)
.group_by(models.TABLE.date)
)
But get the error "value" must appear in the GROUP BY clause or be used in an aggregate function
但是得到错误
"value" must appear in the GROUP BY clause or be used in an aggregate function
While, based on my understanding, using an aggregate function or including "value" in the GROUP BY clause will not provide the desired result.而根据我的理解,使用聚合函数或在 GROUP BY 子句中包含“值”不会提供所需的结果。
What query can I use to get desired rows?我可以使用什么查询来获取所需的行?
I was looking for the distinct clause我正在寻找独特的条款
query = select(TABLE).distinct(
TABLE.date
).order_by(
TABLE.date,
TABLE.created_at.desc(),
)
I had the same problem at the project that I am doing, but after reading documentation about relationships
and distinct
i made this query.我在我正在做的项目中遇到了同样的问题,但是在阅读了有关
relationships
和distinct
文档之后,我提出了这个查询。 You can also try like this, hope it helps.你也可以这样试试,希望对你有帮助。
query = (
select value, created_at, date, count(distinct(date)) from TABLE group by value, created_at, date
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.