實例應用:商城訂單數據統計python
查詢某段時間內的 總訂單數、已支付訂單數、總消費金額、已支付消費金額、筆單價、客單價mysql
代碼以下:sql
#!/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 ''' #####################