繁体   English   中英

通过 python 将销售数据作为只有两位小数的 VARCHAR 附加到 MS SQL-Server 表

[英]Appending sales data to a MS SQL-Server table as a VARCHAR with only two decimal places via python

这是涉及 pandas 和 MS SQL-Server 连接的 python ETL 过程的特定问题。

如果收到的销售数据是一个多于两位小数的数字(例如:$1,245.456),如何将其附加到 VARCHAR 数据类型的销售表中。 sales 列是 VARCHAR,不能更改为其他数据类型。

my_sales_file.xlsx 看起来像这样:

Product | Sales
--------|--------
Apple   | 1235.456
Banana  | 567.54
Pear    | 43.435
Peach   | 432.32

示例代码:

import pandas as pd
import sqlalchemy
from sqlalchemy.types import String

con_string = 'dummy_con_string'
engine = sqlalchemy.create_engine(con_string)

# read the file, force string datatype
df = pd.read_excel('my_sales_files.xlsx', dtype=str)

# round sales to a decimal value
df['Sales'] = df['Sales'].apply(lambda x: str(round(float(x), 2)))

# append to a ms sql table
df.to_sql(name='my_table',
          con=engine,
          if_exists='append',
          dtype={'Sales': String})
SELECT SUM(CAST(Sales as float)
FROM my_table;

结果显示为带有尾随十进制值的小数。

附加验证:

select * from my_table
where LEN(Sales)-CHARINDEX('.',sales) > 2 and CHARINDEX('.'sales) <> 0;

我被一个表格卡住了,该表格将销售数据作为 VARCHAR 并且需要一个解决方案来使用 python 舍入和附加混乱的销售,以便保留所有舍入。

以下将格式化数字并将其四舍五入到小数点后两位。 我倾向于使用try_convert(money,...)它往往更宽容一点。

例子

Declare @YourTable Table ([Product] varchar(50),[Sales] varchar(50))  
Insert Into @YourTable Values 
 ('Apple','$1,245.456')
,('Banana','567.54')
,('Pear','43.435')
,('Peach','432.32')
,('Fig','32')

Select *
      ,AsString = format(try_convert(money,Sales),'0.00') 
 From @YourTable

退货

Product Sales       AsString
Apple   $1,245.456  1235.46  << Notice Rounded and $ and , not an issue
Banana  567.54      567.54
Pear    43.435      43.44
Peach   432.32      432.32
Fig     32          32.00     << Notice two decimals

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM