计算 table 中的数据,不包括重复项
Count data from a table excluding duplicates
我需要计算 table 中的元素。问题是我确实有一个解决方案,但我使用的是从 table 中删除重复项的函数,然后我可以毫无问题地获得计数(但需要一段时间来处理)这是一个我的例子 model/table:
如果我据此进行计数,我将得到以下结果:
3 个已发货,4 个已分配,2 个无状态,1 个已加载。
我需要得到以下结果:2 Shipped(忽略 1 个重复项)、1 Allocated(忽略 3 个重复项)、2 No status(没有重复项)、1 Loaded。
感谢您的宝贵时间,
如果您使用的是 PostgreSQL,则可以通过以下方式使用 DISTINCT ON
Model.objects.order_by('field').dictinct('field').count()
如果您正在使用 MySQL,您可以使用
Model.objects.order_by('field').aggregate(count=Count('field', distinct=True))['count']
您需要order_by
您传递给distinct的字段,there is more information in the docs
我需要计算 table 中的元素。问题是我确实有一个解决方案,但我使用的是从 table 中删除重复项的函数,然后我可以毫无问题地获得计数(但需要一段时间来处理)这是一个我的例子 model/table:
如果我据此进行计数,我将得到以下结果: 3 个已发货,4 个已分配,2 个无状态,1 个已加载。
我需要得到以下结果:2 Shipped(忽略 1 个重复项)、1 Allocated(忽略 3 个重复项)、2 No status(没有重复项)、1 Loaded。
感谢您的宝贵时间,
如果您使用的是 PostgreSQL,则可以通过以下方式使用 DISTINCT ON
Model.objects.order_by('field').dictinct('field').count()
如果您正在使用 MySQL,您可以使用
Model.objects.order_by('field').aggregate(count=Count('field', distinct=True))['count']
您需要order_by
您传递给distinct的字段,there is more information in the docs