简体   繁体   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

This is a specific question for a python ETL process involving pandas and MS SQL-Server, with a sqlalchemy connection.这是涉及 pandas 和 MS SQL-Server 连接的 python ETL 过程的特定问题。

If sales data is received as a number with more than two decimal places (ex: $1,245.456), how can it be appended to a sales table that is a VARCHAR data type.如果收到的销售数据是一个多于两位小数的数字(例如:$1,245.456),如何将其附加到 VARCHAR 数据类型的销售表中。 The sales column is a VARCHAR and cannot be altered to a different datatype. sales 列是 VARCHAR,不能更改为其他数据类型。

my_sales_file.xlsx looks like this: my_sales_file.xlsx 看起来像这样:

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

Example code:示例代码:

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;

results display as a decimal with trailing decimal values.结果显示为带有尾随十进制值的小数。

Additional validation:附加验证:

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

I am stuck with a table that takes in sales data as a VARCHAR and need a solution to for rounding and appending messy sales with python such that all rounding is preserved.我被一个表格卡住了,该表格将销售数据作为 VARCHAR 并且需要一个解决方案来使用 python 舍入和附加混乱的销售,以便保留所有舍入。

The following will format and round the number to two decimals.以下将格式化数字并将其四舍五入到小数点后两位。 I tend to use try_convert(money,...) it tends to be a little more forgiving.我倾向于使用try_convert(money,...)它往往更宽容一点。

Example例子

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

Returns退货

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