Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 基于一个月的最新日期的复杂计数_Sql_Django - Fatal编程技术网

Sql 基于一个月的最新日期的复杂计数

Sql 基于一个月的最新日期的复杂计数,sql,django,Sql,Django,我有一个模型: class HistoricalRecord(models.Model): history_id = models.CharField(max_length=32) type = models.CharField(max_length=8) history_date = models.DateField() 如何根据给定月份的历史id仅获取最新对象,从而获取每种类型的历史记录的计数。例如: 使用这些示例对象: HistoricalRecord.objec

我有一个模型:

class HistoricalRecord(models.Model):
    history_id = models.CharField(max_length=32)
    type = models.CharField(max_length=8)
    history_date = models.DateField()
如何根据给定月份的历史id仅获取最新对象,从而获取每种类型的历史记录的计数。例如:

使用这些示例对象:

HistoricalRecord.objects.create(history_id="ABC1", type="A", history_date=date(2000, 10, 5))
HistoricalRecord.objects.create(history_id="ABC1", type="A", history_date=date(2000, 10, 27))
HistoricalRecord.objects.create(history_id="DEF1", type="A", history_date=date(2000, 10, 16))
HistoricalRecord.objects.create(history_id="ABC1", type="B", history_date=date(2000, 10, 8))
结果应该是:

[
    {
        "type": "A",
        "type_count": 2
    },
    {
        "type": "B",
        "type_count": 0
    }
]
A为2,因为history_id ABC1的最新HistoryRecord对象位于27号,类型为A;另一个是具有history_id DEF1的记录

我试过:

HistoricalRecord.objects.filter(history_date__range(month_start, month_end)).order_by("type").values("type").annotate(type_count=Count("type"))

但是很明显,这是不正确的,因为它得到了这个月的所有值。结果的结构不必与上面的完全相同,只要它清楚地表达了每种类型的计数。

这很可能可以通过使用来完成。另外,将此添加到查询中:

.extra(
    where=["""history_date = (SELECT MAX(history_date) FROM historical_record hr
                              WHERE hr.history_id = historical_record.history_id
                                    AND hr.history_date < %s)"""],
    params=[month_end]
)