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
'''
#####################

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM