目录
1、创建数据库以及表结构
查询语句;
在表创建完成之后记得检查表,排除在导入数据时因为数据表的构建的原因
create database cy;
use cy;
-- bill table
create table bill(
billdate date not null,
billnumber varchar(20) not null default '_',
shopname varchar(20) not null default '_',
billdiscount float not null default '0',
paytime time not null,
tablenumber int not null default '0',
peoplecount int not null default '0'
) charset="utf8";
-- orderdetail table
create table orderdetail(
billnumber varchar(20) not null,
dateil varchar(20) not null,
pay int not null default '0'
) charset="utf8";
-- shopdetail table
create table shopdetail(
shopname varchar(20) not null,
twotable int not null default '0',
threetable int not null default '0',
fourtable int not null default '0',
alltable int not null default '0'
) charset="utf8";
-- 文件路径非中文
load data local infile "文件路径"
into table bill -- 表名
fields terminated by ","
-- 创建单汇总金额表
create table ordergroup(
select billnumber,sum(pay) as pay
from orderdetail
group by billnumber);
-- 创建新单号信息表
create table newbill(
select b.*,o.pay,b.billdiscount*o.pay as rebate
from bill as b
left join ordergroup as o on b.billnumber=o.billnumber);
-- 创建新店面情况表
create table newshopdetail(
select shopdetail.*,(twotable * 2 + threetable * 3 + fourtable * 4) allseats
from shopdetail);
-- 创建创建新点菜明细表
create table neworderdetail(
select shopname,orderdetail.*
from orderdetail
left join bill on orderdetail.billnumber=bill.billnumber);
-- 创建店汇总信息表
create table shoptotal(
select newbill.shopname as 店名,
count(newbill.billnumber) as 单数,
sum(newbill.peoplecount) as 人数,
sum(newbill.rebate) as 折扣总金额,
sum(newbill.pay) 店汇总金额,
sum(newbill.pay)/count(newbill.billnumber) 单均消费,
sum(newbill.pay)/sum(newbill.peoplecount) 人均消费,
newshopdetail.alltable 总台数,
newshopdetail.allseats 总座位数,
count(newbill.billnumber)/newshopdetail.alltable 翻台率,
sum(newbill.peoplecount)/newshopdetail.allseats 上座率,
sum(newbill.rebate)/sum(newbill.pay) 折扣率
from newbill
left join newshopdetail on newbill.shopname=newshopdetail.shopname
group by newbill.shopname);
2、向数据库导入数据
执行此代码需要做一些准备工作:
①安装pandas包;pandas在进行数据的导入时具有更快的速度和效率
②安装pymysql;连接MYSQL数据库的第三方包
代码注意事项:
①//后面跟的是用户名,:后面是用户名所对应的密码@后面的是IP地址以及端口号,再后面就是数据库名称
②读入文件的地址;此处使用的是相对地址,因为所需要的文件在当前目录的data下面,如果不在可以使用绝对路径
数据导入完成后记得检查数据导入是否正确,排除在之后的过程中因为数据库的数据的原因
import pandas as pd
from sqlalchemy import create_engine
# pip install pymysql
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/cy?charset=utf8')
bill = pd.read_csv('./data/bill.csv')
orderdetail = pd.read_csv('./data/order.csv')
shopdetail = pd.read_csv('./data/shop.csv')
bill.to_sql('bill', engine, if_exists='replace', index=False)
orderdetail.to_sql('orderdetail', engine, if_exists='replace', index=False)
shopdetail.to_sql('shopdetail', engine, if_exists='replace', index=False)