簡體   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