查询以获取日期范围内的计数,小计和总计

时间:2018-12-12 14:41:15

标签: sql django postgresql django-models django-orm

说我有一个带有created_at属性的对象。我想拥有 一个查询,将导致给定日期的创建对象计数 (count_小计直到该日期的对象(sub)以及完整的 所有对象的总数({{1)}:

total_

我设法获得了 date | count_ | sub | total_ ------------+--------+-------+------- 2018-10-08 | 1 | 1 | 15 2018-10-11 | 2 | 3 | 15 2018-10-15 | 3 | 6 | 15 2018-10-23 | 4 | 10 | 15 2018-10-24 | 5 | 15 | 15 count_

total_

生成此Obj.objects.annotate( date=Trunc('created_at', 'day', output_field=DateField()) ).values( 'date' ).annotate( count_=Window(expression=Count('id'), partition_by=[F('date')]), total_=Window(expression=Count('id')) ).distinct()

SQL

1 个答案:

答案 0 :(得分:2)

demo: db<>fiddle

您需要cumulative window function。这可以通过添加ORDER BY子句来实现。如果存在,COUNT()将按照您的期望进行累积。如果不存在,则COUNT将占据整个框架。

count(created_at) OVER (ORDER BY created_at) as subtotal

查询

SELECT DISTINCT
    created_at,
    count(created_at) OVER (PARTITION BY created_at) as count_,
    count(created_at) OVER (ORDER BY created_at) as subtotal_,
    count(created_at) OVER () as total_
FROM
    dates

因此,尽管我不太喜欢Django,但我相信您需要这样的一行:

subtotal_=Window(expression=Count('id'), order_by=[F('date')]),