-1
我正在Python中使用以下代碼模板(使用Atom構建/寫入)。如何在Python腳本中執行多個SQL語句?
import pyodbc
import pandas as pd
import win32com.client
cnxn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL
Server}',server ='prodserver', database = 'XXXX')
cnxn.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8')
cnxn.setencoding(str, encoding='utf-8')
cnxn.setencoding(unicode, encoding='utf-8', ctype=pyodbc.SQL_CHAR)
cursor = cnxn.cursor()
script ="""SELECT AccountsCount.AccountClass, COUNT(*) as Count
FROM
(SELECT *
FROM XXXX.dbo.table
where SubNo='001'
AND (DATENAME(WEEKDAY, GETDATE()) = 'Sunday' AND
convert(date,AddDate) = DATEADD(DAY, -2, CAST(GETDATE() as DATE))
) OR
(DATENAME(WEEKDAY, GETDATE()) = 'Monday' AND
convert(date,AddDate) = DATEADD(DAY, -3, CAST(GETDATE() as DATE))
) OR
(DATENAME(WEEKDAY, GETDATE()) = 'Sunday' AND
convert(date,AddDate) = DATEADD(DAY, -2, CAST(GETDATE() as DATE))
) OR
(DATENAME(WEEKDAY, GETDATE()) NOT IN ('Sunday', 'Monday') AND
convert(date,AddDate) = DATEADD(DAY, -1, CAST(GETDATE() as DATE))
)) AS AccountsCount
Group by AccountsCount.AccountClass
"""
df = pd.read_sql_query(script,cnxn)
writer = pd.ExcelWriter ('ExcelFile.xlsx')
df.to_excel(writer, sheet_name = 'Data Export')
writer.save()
xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = ('OtherExcelFile.xlsm')
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run('CopyIntoOutlook')
wb.Save()
xlApp.Quit()
所有我需要做的就是添加第二個和完全獨立的SQL命令,這個腳本它運行絕對完美和做什麼,我需要做的就是以上。我的其他腳本是這樣
script= """ select AccountClass, COUNT(*) as Count
FROM XXXX.dbo.table
where SubNo='001'
AND AddDate >= '1/1/2017'
Group by AccountClass """
我曾與任何沒有運氣,據我已經試過如添加到腳本,任何幫助是非常apprecaited!您會注意到第二個腳本使用的是與原始數據庫相同的表格,我只需要YTD數據以及前一天查看的頂部查詢。
您有什麼問題?只需用'pd.read_sql_query()'執行第二個查詢' – Barmar
爲什麼當你清楚地使用SQL-Server時,你有這個帶標籤的'mysql'? – Barmar
你想要的輸出是什麼?第二個查詢作爲新的Excel工作表?運行相同的過程,但更改'SELECT'語句和目標工作表。 – Parfait