【发布时间】:2021-04-26 04:43:13
【问题描述】:
我正在尝试修复我的数据库中的数据未正确分组的错误,并且想知道是否有一个简单的修复,因为我不是 SQL 大师。
我们正在尝试对特定日期附近的记录进行分组。问题之所以突出,是因为我们正处于新的一年,而新的一年在这一周结束。发生的情况是其中一个日期而不是 2020 年 12 月 27 日,它必须获得一周最后一天的年份并将其变成 2021 年 12 月 27 日。所有的笑话都是关于我们多么希望那时已经是 2021 年,这是一个奇怪的错误,我不确定如何解决它。
这是我认为包含问题的 Python 的违规块:
date = sa.literal_column("to_date(concat(extract(year from {}.created_at),extract(week from {}.created_at)), 'yyyyww')".format(metric_class.__table__,metric_class.__table__))
if 'date_group' in request_args:
group_classname = "".join([part.title() for part in request_args['date_group'].split("_")])
group_class = expand_classes[group_classname]
date = sa.literal_column("to_date(concat(extract(year from {}.created_at),extract(week from {}.created_at)), 'yyyyww')".format(group_class.__table__,group_class.__table__))
编辑:添加请求的信息
metric_class 和 group 类:只是对我们众多表类之一的引用。它们都包含一个 id(主键)和一个 created_at(日期)。
在我的环境中生成的实际查询示例:
SELECT to_date(concat(extract(year from users.created_at),extract(week from users.created_at)), 'yyyyww'), count(users.id) AS count_1
FROM users
WHERE users.deleted_at IS NULL AND users.company_id = '762976f4-8e19-4f1a-a0ef-b205fb8f68f2' AND
users.created_at > '1/21/2020' AND users.role = 2 GROUP BY
to_date(concat(extract(year from users.created_at),extract(week from users.created_at)), 'yyyyww') ORDER BY to_date(concat(extract(year from users.created_at),extract(week from users.created_at)), 'yyyyww') DESC LIMIT 50;
我无法向您展示实际的错误数据,因为它位于我无法访问的生产环境中,但这里是您可能会看到从我的数据中编辑的内容的示例:
to_date | count_1
------------+---------
2021-12-28 | 1
2020-12-16 | 2
2020-12-02 | 1
2020-11-25 | 12
2020-11-18 | 3
2020-11-04 | 2
2020-05-27 | 2
2020-04-01 | 3
2020-03-25 | 1
2020-03-18 | 1
2020-02-12 | 1
【问题讨论】:
-
请创建一个Minimal and Reproducible Example 可以把
metric_class和group_class的相关部分贴出来。你在哪里使用literal_columndate。还有一些示例数据。 -
我添加了我认为相关的信息。
-
您使用的是哪个数据库?
-
如果你使用
.group_by(func.date_trunc('week', Users.created_at))而不是文字列会发生什么? -
到目前为止真的没有运气。但这可能是正确的方向。我会玩弄它,看看我能不能想出正确的组合
标签: python sql sqlalchemy