[英]SQL Python, handling one or many values in Where Statement
我在下面有这个虚拟代码。 我要做的几乎就是创建一个表格,其中包含所有客户及其 ID 的一个或多个部门,该部门或部门在 excel 表中是特定的。 在 excel 单元中,可以列出一个或多个部门。 如果有多个分区,则下面的代码可以工作,但是如果只有一个分区,则代码不起作用,因为我正在创建一个元组,并且 where 子句基本上变成了类似于 where division_id in (92,) 的东西,它运行 SQL 错误。 我如何编写此代码以便它既可以处理多个部门又可以处理单个部门。
代码:
filename = 'test.csv'
division = test.iloc[0][4]
division_tuple = tuple(map(int, division.split(",")))
sql = cs.execute("""
INSERT INTO sample_table_name
select c.customer_id,
c.customer_name
from(
t.customer_id
t.customer_name
from customer_table t
where division_id in {}
group by 1,2) c ;
""".format(division_tuple))
如果 excel 表只有一个列出的分区,我会收到以下错误:
代码错误:
回溯(最后一次调用): division_tuple = tuple(map(int, division.split(","))) AttributeError: 'numpy.int64' object has no attribute 'split'
我还附上了一个单元格的图像,如果有多个,它会是相同的,但像“92,100,203”等。
数据:
它会引发错误: AttributeError: 'numpy.int64' object has no attribute 'split'
这意味着除法变量不是字符串,而是 numpy.int64。
因此,如果有多个值,它会以字符串的形式出现。 但是,如果有一个值,它是 numpy.int64
作为一种解决方法,您可以更改
division_tuple = tuple(map(int, division.split(",")))
至
division_tuple = tuple(map(int, str(division).split(",")))
我已经像这样测试过它:
import numpy
a = numpy.int64(5)
print(str(a).split(','))
我不知道您的除法变量的类型,但从您的错误中称它不是字符串 for.split() 它必须是字符串值
那么你可以尝试将除法更改为字符串 object 以使用 with.split()。
感谢 Shashwat 帮助我修复 Numpy 错误。 实施该更改后,我没有收到 Numpy 错误,而是格式错误。 所以做了下面的改变
filename = 'test.csv'
division = test.iloc[0][4]
division_tuple = tuple(map(int, str(division).split(",")))
sql = cs.execute("""
INSERT INTO sample_table_name
select c.customer_id,
c.customer_name
from(
t.customer_id
t.customer_name
from customer_table t
where division_id in (%s) --changed format here
group by 1,2) c ;
""",(division_tuple)) #and here
尽管这在技术上会使 where 子句在存在单个值时看起来像“where division_id in (92,)”,但这仍然是运行它的正确方法,尽管在 92 之后有尾随逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.