SQL - 等效的Django查询

时间:2014-12-02 16:00:54

标签: django django-queryset

我有一张桌子

+----+------------+
| id | day        |
+----+------------+
|  1 | 2006-10-08 |
|  2 | 2006-10-08 |
|  3 | 2006-10-09 |
|  4 | 2006-10-09 |
|  5 | 2006-10-09 |
|  5 | 2006-10-09 |
|  6 | 2006-10-10 |
|  7 | 2006-10-10 |
|  8 | 2006-10-10 |
|  9 | 2006-10-10 |
+----+------------

我想按频率及其计数进行分组,例如

  

由于日期2006-10-08出现两次,因此频率为2且只有一个日期出现两次,因此总日期1

另一个例子

  

2006-10-102006-10-09都出现4次,因此频率4和频率为4的总日期为2

我期待输出如下

+----------+--------------------------------+
| Freuency | Total Dates with frequency N   |
+----------+--------------------------------+
|  1       | 0                              |
|  2       | 1                              |
|  3       | 0                              |
|  4       | 2                              |
|  n       | f(n)                           |
+----------+--------------------------------+

我有一个SQL查询,经过深思熟虑后编写,我想知道等效的Django查询是什么?

select freq, count(*)
from (select day, count(*) as freq
      from test 
      group by day
     ) d
group by freq;

1 个答案:

答案 0 :(得分:0)

您可以使用aggregation

from django.db.models import Count
MyModel.objects.values('day').annotate(frequency=count('day')).order_by('frequency')