Django 之 distinct、count、sum字段的几种用法

1、distinct 某个字段

sql语句:

SELECT DISTINCT user FROM user_table WHERE create_date =2020-12-08;

model语句:

UserModel.objects.filter(create_date=2020-12-08).values(“user”).distinct()

2、distinct 多个字段

sql语句:

SELECT DISTINCT user, status FROM user_table WHERE create_date =2020-12-08;

model语句:

UserModel.objects.filter(create_date=2020-12-08).values(“user”, “status").distinct()

3、统计 某个字段 count 总数
sql语句:

SELECT COUNT(DISTINCT user) FROM user_table WHERE create_date =2020-12-08;

model语句:

UserModel.objects.filter(create_date=2020-12-08).values(“user”).distinct().count()

4、统计 某个字段 sum 总数
假设某个字段名为 count,

sql语句:

SELECT SUM(count) FROM user_table WHERE create_date =2020-12-08';

model语句:

from django.db.models import Sum
UserModel.objects.filter(create_date=2020-12-08).aggregate(num=Sum(“count”))

5、使用 GROUP BY 统计 COUNT
假设根据 create_date 字段统计:

sql语句:

SELECT create_date, COUNT(user) FROM test_table GROUP BY create_date;

model语句:

from django.db.models import Count
TestTable.objects.values(“create_date”).annotate(count=Count(“user"))

6、使用 GROUP BY 统计 COUNT + DISTINCT
假设根据 create_date 字段统计:

sql语句:

SELECT create_date, COUNT(DISTINCT user) FROM test_table GROUP BY create_date;

model语句:

from django.db.models import Count
TestTable.objects.values(“create_date”).annotate(count=Count(“user”, distinct=True))

**7、使用 GROUP BY 统计 SUM **
假设根据 create_date 字段统计:

sql语句:

SELECT create_date, SUM(speaker_count) FROM test_table GROUP BY create_date;

model语句:

from django.db.models import Sum
TestTable.objects.values(“create_date”).annotate(sum=Sum(“speaker_count"))

你可能感兴趣的:(django,Django去重用法,Djangocount,Django,sum,django分组统计,Django分组求和)