2 回答
TA贡献1865条经验 获得超7个赞
因为Order
是SQL Server 关键字,所以您需要对标识符进行转义,例如使用方括号:[Order]
。否则编译器认为您正在尝试调用该ORDER BY
命令。最好使用表别名来避免重复较长的表名:
sql = """SELECT pi.mrn
, a.lastname
, v.visitnumber
, pi.firstname
, pi.lastname
, a.firstname
, r.lastsigndate
, o.proceduredesclist
, v.facility
, o.completedate
, o.fillerordernumber
FROM
(
(comm4.dbo.[ORDER] o
INNER JOIN comm4.dbo.report r
ON o.reportid = r.reportid)
INNER JOIN
(comm4.dbo.patientinfo pi
INNER JOIN comm4.dbo.visit v
ON pi.patientid = v.patientid)
ON o.visitid = v.visitid
)
INNER JOIN comm4.dbo.accountpersonalinfo a
ON r.signeracctid = a.accountid
WHERE pi.mrn <> 'TEMPORARY'
AND r.lastsigndate >= {ts '2020-09-01 00:00:00'}
AND r.lastsigndate < {ts '2020-10-01 00:00:00'}
ORDER BY r.lastsigndate
, pi.mrn
"""
虽然带括号的嵌套连接是允许的(让人想起 MS Access SQL),但您可以避免这种嵌套,因为所有连接都是INNER. 更扁平的 SQL 语句可以提高可读性和可维护性。
sql = """SELECT pi.mrn
, a.lastname
, v.visitnumber
, pi.firstname
, pi.lastname
, a.firstname
, r.lastsigndate
, o.proceduredesclist
, v.facility
, o.completedate
, o.fillerordernumber
FROM comm4.dbo.[ORDER] o
INNER JOIN comm4.dbo.report r
ON o.reportid = r.reportid
INNER JOIN comm4.dbo.visit v
ON o.visitid = v.visitid
INNER JOIN comm4.dbo.patientinfo pi
ON pi.patientid = v.patientid
INNER JOIN comm4.dbo.accountpersonalinfo a
ON r.signeracctid = a.accountid
WHERE pi.mrn <> 'TEMPORARY'
AND r.lastsigndate >= {ts '2020-09-01 00:00:00'}
AND r.lastsigndate < {ts '2020-10-01 00:00:00'}
ORDER BY r.lastsigndate
, pi.mrn
"""
TA贡献1836条经验 获得超4个赞
你的sql语法中有几个错误,执行连接时不需要额外的括号“((”。你不必担心缩进SQL语句,但是python缩进和换行可能有点棘手。为了简化你的代码,你可以在Python中利用多行字符串(即使用""" some string """),例如。
import pymssql
conn = pymssql.connect(server= 'xxx',
user= 'xxx',
password= 'xxx',
database= 'xxx'
)
cursor = conn.cursor()
sql = """
SELECT
PatientInfo.MRN,
AccountPersonalInfo.LastName,
Visit.VisitNumber,
PatientInfo.FirstName,
PatientInfo.LastName,
AccountPersonalInfo.FirstName,
Report.LastSignDate,
Orders.ProcedureDescList,
Visit.Facility,
Orders.CompleteDate,
Orders.FillerOrderNumber
FROM
Comm4.dbo.Order Orders
INNER JOIN
Comm4.dbo.Report Report ON Orders.ReportID=Report.ReportID
INNER JOIN
Comm4.dbo.Visit Visit ON Orders.VisitID=Visit.VisitID
INNER JOIN
Comm4.dbo.PatientInfo PatientInfo ON PatientInfo.PatientID=Visit.PatientID
INNER JOIN
Comm4.dbo.AccountPersonalInfo AccountPersonalInfo ON
Report.SignerAcctID=AccountPersonalInfo.AccountID
WHERE
PatientInfo.MRN<>'TEMPORARY' AND
Report.LastSignDate>={ts '2020-09-01 00:00:00'} AND
Report.LastSignDate<{ts '2020-10-01 00:00:00'}
ORDER BY
Report.LastSignDate, PatientInfo.MRN
"""
cursor.execute(sql)
row = cursor.fetchone()
conn.close()
print(row)
添加回答
举报