Cx_Oracle(Python3.6)SQL查询GROUP BY导致ValueError - 在SQL Developer中运行正常

时间:2017-06-09 17:06:20

标签: python sql oracle oracle-sqldeveloper cx-oracle

系统信息:

print(cx_Oracle.clientversion())    
(12, 2, 0, 1, 0)
print(cx_Oracle.version) 
6.0b2
print(sys.version)
3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]

我有一个正在运行的查询,它在SQL Developer中正常工作但是在使用cx_Oracle在python中运行时引发错误。它似乎与GROUP BY子句有某种关系,因为当SUMGROUP BY被删除时,查询在cx_Oracle中运行。

SQL命令:

SELECT prop_code, forecast, sum(uc_fc) as remaining_fc
FROM my_table
WHERE
prop_code = 'MYPROP'
AND stay_Date = '01-MAY-17'
GROUP BY prop_code, forecast;

SQL Developer中的RETURNS:

+-------------+------------+-------------------------+
| "PROP_CODE" | "FORECAST" |     "REMAINING_FC"      |
+-------------+------------+-------------------------+
| MYPROP      |         17 | 3858.2210740962656178   |
| MYPROP      |          8 | 4599.4697955023602118   |
| MYPROP      |          4 | 798.79072149551767364   |
| MYPROP      |          7 | 1096.30162478218624302  |
| MYPROP      |         18 | 4016.37933889910515332  |
| MYPROP      |          1 | 4793.6514493804123866   |
| MYPROP      |          2 | 10070.756632866636683   |
| MYPROP      |          3 | 29910.550761344399349   |
| MYPROP      |          5 | 1820.4588262721241473   |
| MYPROP      |          6 | 15406.887917698571224   |
| MYPROP      |         99 | 3846.232477937824844934 |
+-------------+------------+-------------------------+

python中的SQL查询:

forecast_query = '''SELECT prop_code, forecast, \
sum(uc_fc) as remaining_fc \
FROM OY_UNC_STYDT_FCST_UPD_ARCH \
WHERE prop_code = 'MYPROP' \
AND stay_Date = '01-MAY-17' \
GROUP BY prop_code, forecast'''

运行它的代码:

start = time.time()
my_dsn = cx_Oracle.makedsn(host='myhost', port=1560, sid='mysid')
con = cx_Oracle.Connection(user= 'username', password='pass', dsn = my_dsn)
cur = con.cursor()
cur.execute(forecast_query)
forecast_results = cur.fetchall()
con.close()

返回此错误:

ValueError: invalid literal for int() with base 10: '3858.2210740962656178'

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我能够通过强制CAST作为float参数到我希望求和的列来运行它。我不知道为什么cx_Oracle无法处理查询。可能是一个错误?

有效的SQL查询:

forecast_query = '''SELECT prop_code, demand_forecast_segment_id, \
cast(sum(uc_fc) as float) as remaining_fc \
FROM MY_TABLE\
WHERE prop_code = 'MYPROP' \
AND stay_Date = '01-MAY-17' \
GROUP BY prop_code, forecast'''

答案 1 :(得分:0)

这是由于模块中的错误已修复。请参阅此问题:https://github.com/oracle/python-cx_Oracle/issues/34