#导入模块
from django.db.models import Avg
from django.db.models import Max
from django.db.models import FloatField
from django.db.models import Count
from django.db.models import Sum
#django 聚合函数
#计算总和 .count()
datatime_log.objects.count()
datatime_log.objects.filter(userid_id="1").count()
#聚合函数汇总
#Avg() 返回给定表达式的平均值
datatime_log.objects.aggregate(Avg('dosage'))
datatime_log.objects.aggregate(allavg = Avg('dosage')) #指定字典名称
datatime_log.objects.aggregate(allavg = Avg('dosage'),max=Max("dosage")) #多聚合
#Count() 返回相关的对象数
#Max() 返回最大值
#Min() 返回最小值
#StdDev() 返回提供的表达式中数据的标准偏差
#Sum() 计算给定表达式的所有值的总和
datatime_log.objects.filter(userid = "1").aggregate(Sum('unit')) #根据条件执行
#Variance() 返回提供的表达式中数据的方差
#mysql
#datetime字段查询 同日期下记录总数
select count(distinct date_format(datetime, '%Y-%m-%d %H')) from treatment_record_datatime_log where userid_id = '1' ;
#datetime字段查询 同日期 同小时 不同分秒下记录总数
select count(distinct date_format(datetime, '%Y-%m-%d %H')) from treatment_record_datatime_log where userid_id = '1' ;
#django 给定时间条件返回符合的条目
#dates() datetimes()
#dates kind应该是"year","month","week","day", datetimes的kind追加 "hour","minute",或"second"
#day month会自动区分年份
datatime_log.objects.dates('datetime',"day").filter(userid = 1).count(); # dates返回日期不同的结果集 count 计算总数
#给表起一个别名
select count(distinct date_format(datetime, '%Y-%m-%d %H')) AS countdate from treatment_record_datatime_log where userid_id = '1' ;
#django执行原生SQL语句
m = datatime_log.objects.raw("select * from treatment_record_datatime_log where userid_id = '1'")