python - 通过 python 将销售数据作为 VARCHAR 附加到 MS SQL-Server 表中,只有两位小数
问题描述
这是一个涉及 pandas 和 MS SQL-Server 的 python ETL 过程的特定问题,具有 sqlalchemy 连接。
如果收到的销售数据是一个多于两位小数的数字(例如:$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
推荐阅读
- mysql - 如何获取单个整数/浮点列的总和达到某个值的行
- c++ - 从c ++ 17中的文件中读取行
- jquery - 如何将光标聚焦在评论框中的第一行?
- streaming - 何时在黑暗中使用轮询和流式传输
- mongodb - 什么是稀疏?MongoDB中稀疏的目的是什么?
- python - 使用 XPath 和 Scrapy 从下一个节点的子节点中提取文本
- python - selenium with IE:点击按钮下载文件,再点击其他按钮,进程会卡住
- python - 如何验证来自原始 HTML 表单的发布请求(未使用 django 表单)
- java - 使用正则表达式屏蔽以下格式
- azure-application-insights - 是否可以在应用程序洞察力中获得 customDimensions["--"] 动态属性?我们可以在 kusto 查询中编写循环吗