2014-12-02 84 views
0

我有一個表SQL - 等效的Django查詢

+----+------------+ 
| 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; 
+0

你能不能給我們你的Django模型? – wolendranh 2014-12-02 16:11:04

回答

0

您可以使用aggregation

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