python - Django 从子查询中选择
问题描述
我想使用窗口函数进行查询,然后通过对子查询的聚合进行一些分组。但我无法使用 ORM 方法。它会回来aggregate function calls cannot contain window function calls
有什么方法可以在不使用的情况下进行如下 SQL 的查询.raw()
SELECT a.col_id, AVG(a.max_count) FROM (
SELECT col_id,
MAX(count) OVER (PARTITION BY part_id ORDER BY part_id) AS max_count
FROM table_one
) a
GROUP BY a.col_id;
例子
table_one
| id | col_id | part_id | count |
| -- | ------ | ------- | ----- |
| 1 | c1 | p1 | 3 |
| 2 | c2 | p1 | 2 |
| 3 | c3 | p2 | 1 |
| 4 | c2 | p2 | 4 |
首先,我想获得基于 part_id 的最大基数
| id | col_id | part_id | count | max_count |
| -- | ------ | ------- | ----- | --------- |
| 1 | c1 | p1 | 3 | 3 |
| 2 | c2 | p1 | 2 | 3 |
| 3 | c3 | p2 | 1 | 4 |
| 4 | c2 | p2 | 4 | 4 |
最后通过 col_id 得到 max_count 组的平均值
| col_id | avg(max_count) |
| ------ | -------------- |
| c1 | 3 |
| c2 | 3.5 |
| c3 | 4 |
我现在拥有的模型
def Part(models.Model):
part_id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
name = models.CharFields()
def Col(models.Model):
part_id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
name = models.CharFields()
def TableOne(models.Model):
id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
col_id = models.ForeignKey(
Col,
on_delete=models.CASCADE,
related_name='table_one_col'
)
part_id = models.ForeignKey(
Part,
on_delete=models.CASCADE,
related_name='table_one_part'
)
count = models.IntegerField()
我想在分区后进行分组。这是我所做的查询,它会带来错误。
query = TableOne.objects.annotate(
max_count=Window(
expression=Max('count'),
order_by=F('part_id').asc(),
partition_by=F('part_id')
)
).values(
'col_id'
).annotate(
avg=Avg('max_count')
)
解决方案
您可以在 Django 中使用子查询,不需要使用窗口函数。首先,子查询是一个查询Part
集,用最大计数注释TableOne
from django.db.models import Avg, Max, Subquery, OuterRef
parts = Part.objects.filter(
id=OuterRef('part_id')
).annotate(
max=Max('table_one_part__count')
)
然后TableOne
用子查询中的最大计数注释查询集,values
在我们想要分组的列上执行 ( col_id
),然后再次用平均值注释以生成所需的输出
TableOne.objects.annotate(
max_count=Subquery(parts.values('max')[:1])
).values(
'col_id'
).annotate(
Avg('max_count')
)
推荐阅读
- python - 如何使用 Pandas 读取和查询 txt 的标题?
- html - 有没有办法为 router.url 应用通用路径?
- xamarin.forms - 夏令时没有坚持
- batch-file - 如何将 FOR 循环中的每个变量输出到它自己的文件
- ruby-on-rails - Google::Cloud::Translate.new 在生产环境中提出的未初始化常量 Google::Cloud
- python - 如何将代码转换为列表理解
- javascript - WebStorm 给我关于缺少分号的警告,即使 TSLint 说永远不要使用它们
- python - django 视图中的依赖注入
- c++ - 如何以编程方式更改基于对话框的窗口的大小和位置?
- excel - 如何从 SAP PR 中的附件中获取文件名文本