美文网首页
django orm分组聚合

django orm分组聚合

作者: Aedda | 来源:发表于2021-10-19 17:02 被阅读0次

    annotate分组

    # 原始SQL
    SELECT start_date, plat_account, site_code, SUM(sessions) AS sessions  FROM crl_reports_business_reports WHERE start_date >= '2021-9-30'  GROUP BY plat_account, start_date, site_code  ORDER BY plat_account, site_code, start_date;
    
    # ORM
    CrlReportsBusinessReports.objects.filter(start_date__gte=datetime.datetime.now().date() - datetime.timedelta(days=20)).values('plat_account', 'site_code', 'start_date').annotate(count_=Sum('sessions')).order_by('plat_account', 'site_code', 'start_date')
    
    # ORM生成的SQL
    SELECT `crl_reports_business_reports`.`plat_account`, `crl_reports_business_reports`.`site_code`, `crl_reports_business_reports`.`start_date`, SUM(`crl_reports_business_reports`.`sessions`) AS `count_` FROM `crl_reports_business_reports` WHERE `crl_reports_business_reports`.`start_date` >= 2021-09-29 GROUP BY `crl_reports_business_reports`.`plat_account`, `crl_reports_business_reports`.`site_code`, `crl_reports_business_reports`.`start_date` ORDER BY `crl_reports_business_reports`.`plat_account` ASC, `crl_reports_business_reports`.`site_code` ASC, `crl_reports_business_reports`.`start_date` ASC
    

    aggregate聚合

    很简单就是查询一个数据集的某个字段的最大值、最小值、平均数、求和、计数等,返回值是字典格式

    相关文章

      网友评论

          本文标题:django orm分组聚合

          本文链接:https://www.haomeiwen.com/subject/yzilnltx.html