• python pymysql 数据查询


    实例应用:商城订单数据统计

          查询某段时间内的 总订单数、已支付订单数、总消费金额、已支付消费金额、笔单价、客单价

    代码如下:

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    
    import pymysql
    from datetime import date
    
    try:
        # 连接数据库
        conn = pymysql.connect(
            host='******.com',
            user = 'test',
            password = 'test',
            db = 'market_test',
            charset = 'utf8'
        )
    except:
        print("连接数据库失败")
        exit(-1)
    
    cur = conn.cursor()
    
    timeStart = date(2019,8,2)
    timeEnd = date(2019,8,16)
    print("日期:", timeStart,"~",timeEnd)
    
    # 查询某个期间所有订单数(已支付+未支付)
    sql_countAll = "select count(*) from record where createtime>'%s' and createtime<'%s';" %(timeStart, timeEnd)
    cur.execute(sql_countAll)
    countAll = cur.fetchall()[0][0]
    print("订单数:",countAll)
    
    # 查询某个期间已支付订单数
    sql_countPay = "select count(*) from record where createtime>'%s' and createtime<'%s' and payStatus='2';" %(timeStart, timeEnd)
    cur.execute(sql_countPay)
    countPay = cur.fetchall()[0][0]
    print("已支付订单数:", countPay)
    
    # 查询某个期间的下单总额(已支付+未支付)
    sql_amountAll = "select sum(amount) as total from record where createtime>'%s' and createtime<'%s';" %(timeStart, timeEnd)
    cur.execute(sql_amountAll)
    # 获得的数值类型是decimal,需要转化为float进行运算,否则会报错
    amountAll = float(cur.fetchall()[0][0])/100
    print("消费金额:%.2f" %amountAll)
    
    # 查询某个期间已支付的订单金额
    sql_amountPay = "select sum(amount) as total from record where createtime>'%s' and createtime<'%s' and payStatus='2';" %(timeStart, timeEnd)
    cur.execute(sql_amountPay)
    # 获得的数值类型是decimal,需要转化为float进行运算,否则会报错
    amountPay = float(cur.fetchall()[0][0])/100
    print("已支付消费金额:%.2f" %amountPay)
    
    # 查询某个期间下单的用户数(已支付+未支付,用户去重)
    sql_userCountPay = "select count(*) from record where createtime>'%s' and createtime<'%s' group by buyerID;" %(timeStart, timeEnd)
    userCountPay=float(cur.execute(sql_userCountPay))
    
    if countPay==0:
        print("无支付用户")
    else:
        print("笔单价:%.2f" %(amountPay/countPay))
    if userCountPay == 0:
        print("无下单用户")
    else:
        print("客单价:%.2f" %(amountPay/userCountPay))
    
    cur.close()
    conn.close()
    
    #####################
    '''
    结果:
    日期: 2019-08-02 ~ 2019-08-16
    订单数: 445
    已支付订单数: 284
    消费金额:147642.00
    已支付消费金额:78025.00
    笔单价:274.74
    客单价:268.13
    '''
    #####################
  • 相关阅读:
    Object detection overview
    CMU: A Baseline for 3D Multi-Object Tracking
    A Review of Visual Trackers and Analysis of its Application to Mobile Robot
    js回顾学习笔记
    写给.NET开发者的Python教程(二):基本类型和变量
    钽电容 Case B 和 MLCC 1210 区别
    linux sed命令就是这么简单
    shell 字符串处理汇总(查找,替换等等)
    linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 )
    php 给定时间戳 加一月 如果下一月天数不够就返回下一月最后一天
  • 原文地址:https://www.cnblogs.com/belle-ls/p/11506879.html
Copyright © 2020-2023  润新知